我在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");
文件已创建但为空。没有异常被抛出。我以前从未见过这个,我被困在这里;我只需要编写一些调试输出。
请告知。
答案 0 :(得分:47)
StreamWriter默认是缓冲的,这意味着在收到Flush()或Close()调用之前它不会输出。
如果您愿意,可以通过设置AutoFlush属性来更改它。否则,只需:
StreamWriter tw = new StreamWriter("C:\\mycode\\myapp\\logs\\log.txt");
// write a line of text to the file
tw.Write("test");
tw.Close(); //or tw.Flush();
答案 1 :(得分:6)
使用
System.IO.File.WriteAllText(@"path\te.txt", "text");
答案 2 :(得分:5)
既不冲洗也不关闭也不处置。 试试这个
using (StreamWriter tw = new StreamWriter(@"C:\mycode\myapp\logs\log.txt"))
{
// write a line of text to the file
tw.Write("test");
tw.Flush();
}
或我的偏好
using (FileStream fs = new FileStream( @"C:\mycode\myapp\logs\log.txt"
, FileMode.OpenOrCreate
, FileAccess.ReadWrite) )
{
StreamWriter tw = new StreamWriter(fs);
tw.Write("test");
tw.Flush();
}
答案 3 :(得分:3)
完成写作后,您需要关闭或刷新StreamWriter。
tw.Close();
或
tw.Flush();
但最佳做法是将输出代码包装在using语句中,因为StreamWriter实现了IDisposable:
using (StreamWriter tw = new StreamWriter("C:\\mycode\\myapp\\logs\\log.txt")){
// write a line of text to the file
tw.Write("test");
}
答案 4 :(得分:3)
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();
答案 5 :(得分:1)
Ya在VB.net中这不是必需的,但在CSharp看来,你需要一个Writer.Flush调用来强制写入。当然,Writer.Close()也会强制刷新。
我们还可以设置StreamWriter实例的AutoFlush属性:
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.
来自:http://msdn.microsoft.com/en-us/library/system.io.streamwriter.autoflush(v=vs.110).aspx
答案 6 :(得分:0)
替代
FileStream mystream = new FileStream("C:\\mycode\\myapp\\logs\\log.txt",
FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter tw = new StreamWriter(mystream);
tw.WriteLine("test");
tw.close();
答案 7 :(得分:0)
尝试关闭文件或将\n
添加到
tw.WriteLine("test");
tw.Close();