Marek
Marek

Reputation: 3575

WriteLine to .txt for each line in richTextBox

Hello I have this line of code to write every line of richTextBox into my .txt file but at the final the txt file is empty but when debug it reads every line. May I know how this code should be improved to do what I want?

                string Path = (@"C:\Users\x\Documents\Visual Studio 2012\Projects\MTest\txtCmdLog.txt");
            StreamWriter sw = new StreamWriter(File.Open(Path, System.IO.FileMode.Append));

            for (int i = 0; i <= txtCmdLog.Lines.Length; i++)
            {
                 sw.WriteLine(txtCmdLog.Lines[i] + "\n");

            }

            sw.Close();

Thank you for your time.

Upvotes: 0

Views: 982

Answers (3)

Sudhakar Tillapudi
Sudhakar Tillapudi

Reputation: 26209

Points to remember:

1.you need to loop through 0 to lines.Length-1.so remove = in <= condition.

2.for disposing the StreamWriter object use using{} block so that you don't need to call close(). Diposal of StreamWriter object will be taken care by using {} block

        string Path = (@"C:\Users\x\Documents\Visual Studio 2012\Projects\MTest\txtCmdLog.txt");
        using(StreamWriter sw = new StreamWriter(File.Open(Path, System.IO.FileMode.Append)))
        {
            for (int i = 0; i < txtCmdLog.Lines.Length; i++)
            {
                 sw.WriteLine(txtCmdLog.Lines[i] + "\n");

            }

        }

Upvotes: 2

swandog
swandog

Reputation: 749

Change your loop to:

for (int i = 0; i < txtCmdLog.Lines.Length; i++)
{
    sw.WriteLine(txtCmdLog.Lines[i]);
}

Don't use <= in the loop's condition check. You also don't need to append a newline character in the call to WriteLine, since that method already writes a newline.

Upvotes: 2

Will Dean
Will Dean

Reputation: 39500

The easy way to do this is:

File.WriteAllLines(filename, arrayOfStrings);

Upvotes: 1

Related Questions