Read/Write To Text File

RwCC 0 Tallied Votes 230 Views Share

This seems to come up every so often, so thought I would add it here so people can have a look if they search the site.

Reading and writing to a text file is a very basic thing in C#, most of us have to do it from very early on and several times later. It's not exactly secure (as you can obviously just open it) so shouldn't be used for passwords or user details.

I will also provide code for reading specific lines in an array of text.

// Write to text file
// The output will be in your Bin/Debug folder by default, this can be changed by adding your own path

                System.IO.StreamWriter StreamWriter1 =
                new System.IO.StreamWriter("myFile.txt");
                StreamWriter1.WriteLine(textBox1.Text);
                StreamWriter1.Close();


// Read the text file
            System.IO.StreamReader StreamReader1 =
            new System.IO.StreamReader("myFile.txt");
            textBox1.Text = StreamReader1.ReadToEnd();
            StreamReader1.Close();

// Write to specific lines in a text file
// Note that the first line is [0]
            StreamWriter writer = new StreamWriter("myFile.txt");
            writer.WriteLine("Line1");
            writer.WriteLine("Line2");
            writer.WriteLine("Line3");
            writer.WriteLine("Line4");
            writer.Close();

// Read from specific lines in a text file
// Note that the first line is [0]

StreamReader reader = new StreamReader("myFile.txt");
            string strAllFile = reader.ReadToEnd().Replace("\r\n", "\n").Replace("\n\r", "\n");
            string[] arrLines = strAllFile.Split(new char[] { '\n' });
            textBox1.Text = arrLines[0];
            textBox2.Text = arrLines[1];
            reader.Close();

// The output of this will be textBox1 will say "Line1" and textBox2 will say "Line2"
andy999 0 Newbie Poster

Thanks for this code . i am a beginer in the c#. I have a question that if there has been listview in place of text box, then how the data of the listview can be written in text form.
thanks.

Member Avatar for ovidiu_b13
ovidiu_b13

If I want to write only on the third line, and not delete the other lines in the file? for example i have

line1 \n
line2 \n
line3 \n
line4 \n

and i want to replace whatever is written on the third line with something else, without modifing or deleting the other lines?

How do I do that?

Vengeful 0 Newbie Poster

Would accessing a particular character be then: arrline[1][1].ToString(); ??

Vengeful 0 Newbie Poster

Ok stupid question, my bad, it is in fact that....

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.