StreamWriter.WriteLine () is not working

I am trying to write several lines, one at a time, in a .txt file using StreamWriter.WriteLine (not static).

const string filename = "BasicTestInfo.txt"; using (var writer = new StreamWriter(filename, false)) { writer.WriteLine("{0} 350 200 200 10 2 28 20 200 2500 1200 1 1", Player1); writer.WriteLine("{0} 300 150 150 4 2 15 18 150 2500 1000 1 0", Player2); writer.WriteLine("{0} 200 140 450 25 14 10 70 4500 2500 750 1 1", Player3); writer.WriteLine("{0} 175 120 400 15 3 8 50 3000 2500 850 1 0", Player4); writer.WriteLine("{0} 300 100 300 8 1 4 30 1000 2500 1200 1 0", Player5); writer.WriteLine("{0} 450 310 450 20 5 5 35 1500 2500 700 1 1", Player6); } 

Each of the player’s objects is a constant constant. If I run this with a different file name (aka BasicTestInfo2.txt), it creates this file in bin.Debug, but it is empty. I know that I get to the inside of the block used (I place Console.WriteLine there), and I know that I want to trim, so I use false to add (although replacing false with true or no parameter does not fix the problem at all).

The main problem is that even if the file is created, there are no lines of text in the file.

+6
source share
4 answers

Yes, it’s true that in VB.net this (exclusive flash) is not needed with the default settings, but with C # you need a call to Writer.Flush to force it to write. Of course, Writer.Close () would also force a flash. Alternatively, we can set the AutoFlush property of the StreamWriter instance:

 sw.AutoFlush = true; // Gets or sets a value indicating whether the StreamWriter // will flush its buffer to the underlying stream after every // call to StreamWriter.Write. 

From: http://msdn.microsoft.com/en-us/library/system.io.streamwriter.autoflush(v=vs.110).aspx

Please note: the "using" construct will eliminate the exclusive flash, but many people land here only based on the topic of this question, and this is the lowest hanging fruit when it encounters a problem.

+6
source

The code shown looks great.

If I were to guess, I would suspect that there is an exception (perhaps from the dodgy implementation of ToString on Player ) that you swallow somewhere.

Go through the code to find out what happens when you go through each next WriteLine , and whether it goes to the end of the using block without errors.

+3
source

close writer

writer.close ();

It worked for me.

+2
source

I had a problem with similair.

I fixed it this way, just put your string in String.Format ():

 writer.WriteLine(String.Format("{0} 350 200 200 10 2 28 20 200 2500 1200 1 1", Player1)); 
-1
source

All Articles