ShadyOrb09 ShadyOrb09 - 3 months ago 9
C# Question

How do I set a textbox's text to a line in a file contained in a string?

Here's the code:

public Form1()
{
string[] reader = File.ReadAllLines(@"F:\Bioshock2SP.ini");

foreach (string lines in reader)
{
if (lines.Contains("VoVolume="))
{
lines.Substring(lines.Length -2);
TextBox.Text = lines; //Exception
}
}

InitializeComponent();
}


I'm trying to find a line in a file and make only the actual setting part of the file show in the textbox. For example I want to find the line containing "VoVolume=55", but I only want, "55" to show in the textbox or even just, "1.534".

I keep getting an exception when I launch the program.
Any ideas?

Exception Details:


NullReferenceException was unhandled.

An unhandled exception of type 'System.NullReferenceException'
occurred in EditingTextFromFile.exe

Additional information: Object reference not set to an instance of an
object.

Answer

Ok. First, you can't use the textBox if it hasn't been initialized. You need to make sure InitializeComponent is run first. This is what is causing your exception. Second, that Substring is not doing anything as you're not using the output value.

Here is your code slightly altered to correct those two issues :

public Form1()
{
    InitializeComponent();
    string[] reader = File.ReadAllLines(@"F:\Bioshock2SP.ini");
    foreach (string lines in reader)
    {
        if (lines.Contains("VoVolume="))
        {
            lines = lines.Substring(lines.Length - 2);
            TextBox.Text = lines.Split(new string[] { "=" }, StringSplitOptions.None).Last();
        }
    }   
}

And TextBox is a terrible name for a TextBox instance.

Edit : I've used the code from Mike's answer.

Comments