Question

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.

Était-ce utile?

La solution

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)

Autres conseils

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top