StreamWriter.WriteLine() is not working

你说的曾经没有我的故事 提交于 2019-12-04 01:07:39

问题


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

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 objects are string cosntants. If I run this with a different filename (a.k.a. BasicTestInfo2.txt) it creates that file in the bin.Debug, but it's empty. I know that I am reaching the inside of the using block (I put a Console.WriteLine in there), and I know that I want to Truncate which is why I am using false for append (Although replacing the false with true or no parameter at all does not fix the problem).

The basic problem is that even though the file gets created, there are no lines of text in the file.


回答1:


Yes it is true that in VB.net this (an exclusive flush) was not needed with the default settings but with C# you need a Writer.Flush call to force the write. Of course - Writer.Close() would force the flush as well. 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

Note that: the "using" construct will obviate an exclusive flush, but a lot of people are landing here just on the basis of subject of this question and this is the lowest hanging fruit when faced with the issue.




回答2:


close the writer

writer.close();

That workedfor me.




回答3:


The code shown looks fine.

If I had to guess, I'd suspect that there is an exception (perhaps from a dodgy ToString implementation on Player) that you are swallowing somewhere.

Step through the code to see what happens as you go over each successive WriteLine, and whether it goes all the way to the end of the using block without an error.




回答4:


I had similair problem.

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

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


来源:https://stackoverflow.com/questions/14009683/streamwriter-writeline-is-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!