StreamWriter.Write doesn't write to file; no e

2019-01-08 01:25发布

My code in C# (asp.net MVC)

StreamWriter tw = new StreamWriter("C:\\mycode\\myapp\\logs\\log.txt");

// write a line of text to the file
tw.Write("test");

The file is created but is empty. No exception is thrown. I have never seen this before and I am stuck here; I just need to write some debugging output.

Please advise.

8条回答
2楼-- · 2019-01-08 02:03

Use

System.IO.File.WriteAllText(@"path\te.txt", "text");
查看更多
在下西门庆
3楼-- · 2019-01-08 02:06
FileStream fs = new FileStream("d:\\demo.txt", FileMode.CreateNew,
                               FileAccess.Write);
StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.ASCII);
int data;

sw.Write("HelloWorld");

sw.Close();
fs.Close();
  • The problem is when StreamWriter Object is created with reference of FileStream Object , SW object will be always expecting some data till SW object is Closed.
  • So After using sw.Close(); Your Opened File will get closed and get ready for showing Output.
查看更多
迷人小祖宗
4楼-- · 2019-01-08 02:07

Try to close the file or add \n to the line such as

tw.WriteLine("test");
tw.Close();
查看更多
兄弟一词,经得起流年.
5楼-- · 2019-01-08 02:08

an alternative

FileStream mystream = new FileStream("C:\\mycode\\myapp\\logs\\log.txt",    
FileMode.OpenOrCreate, FileAccess.Write);           
StreamWriter tw = new StreamWriter(mystream); 
tw.WriteLine("test");
tw.close();
查看更多
迷人小祖宗
6楼-- · 2019-01-08 02:20

Ya in VB.net this was not needed but it seems with CSharp you need a Writer.Flush call to force the write. Of course Writer.Close() would force the flush as well.

We can also 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

查看更多
不美不萌又怎样
7楼-- · 2019-01-08 02:25

You need to either close or flush the StreamWriter after finishing writing.

tw.Close();

or

tw.Flush();

But the best practice is to wrap the output code in a using statement, since StreamWriter implements IDisposable:

using (StreamWriter tw = new StreamWriter("C:\\mycode\\myapp\\logs\\log.txt")){
// write a line of text to the file
tw.Write("test");
}
查看更多
登录 后发表回答