-1

Here's my code:

for (int j = 0; j < bufferreader.Length; j++)
{
    using (StreamWriter sw = File.AppendText(@"C:\Users\yamald\Documents\Normal.data"))
    {
        //sw.Write();

        if (bufferreader.length != null)
        {
            sw.Write(bufferreader[j] + ",");
        }
        else
        {
            sw.WriteLine("\n");
        }
    }
}

How can I write a "\n" at the end of array to my file? The else command does not run.

svick
  • 236,525
  • 50
  • 385
  • 514
Yamur
  • 339
  • 6
  • 20

2 Answers2

0

You should probably just make the StreamWriter object before everything else and have it available until the loop has finished, then just write the newline after the loop, like this:

using (StreamWriter sw = File.AppendText(@"C:\Users\yamald\Documents\Normal.data"))
{
    for (int j = 0; j < bufferreader.Length; j++)
    {
        sw.Write(bufferreader[j] + ",");
    }
    sw.WriteLine("\n");
}

It's also probably better to use a while loop and do something like while(bufferreader.length != null) instead of the for loop and if statement, but that's up to you and I haven't used bufferreader in a while so wouldn't know the exact syntax for that.

However, the reason for why the else never gets executed is (as EoiFirst correctly said) that you're not actually changing bufferreader.length so it won't ever be null.

SharkofMirkwood
  • 11,483
  • 2
  • 17
  • 25
  • Thank you, I thought the `while` will not work once I am looking to write the content of the array into a file then write `\n` at the end for each row. That will produce a dataset. – Yamur Jul 18 '13 at 12:21
  • You can still use a while loop, and write the `/n` after the loop (the same as you're doing after this solution). It will just be one while loop for each line. However, it won't really make much of a difference so don't worry about it. – SharkofMirkwood Jul 18 '13 at 12:43
  • I completely worry about your solution but I hope to give me an example. Why this negative point to my subject? `while(bufferreader.lenght != null) sw.Write(bufferreader[i] + ",");` Is that right? – Yamur Jul 18 '13 at 12:50
  • That won't work because bufferreader.length will never become null (so it would create an infinite loop). You could try `while(!bufferreader.EndOfStream) sw.Write(bufferreader.Next() + ",")`. I just found the method here: http://msdn.microsoft.com/en-us/library/system.io.streamreader.aspx – SharkofMirkwood Jul 18 '13 at 19:24
  • Hi, could you give me a positive vote. I cann't post any question now – Yamur Jul 23 '13 at 08:17
0

You need to place sw.WriteLine("\n"); after the for loop.

As the loop stops when j = bufferreader.length, the if statement is always true.

Also, I think that bufferreader.length will never be null as you never modify this variable. I think what you need is :

if (bufferreader.length > j)
Yabada
  • 1,728
  • 1
  • 15
  • 36