我曾尝试在文本文件上写一个字符串,但它没有写任何内容,也没有例外。我的代码是:
public void CreateLog(string sLogInfo)
{
string sDestionation = null;
string sFileName = DateTime.Now.ToString("yyyyMMdd") + "_log.txt";
sDestionation = @"D:\Log\";
//sDestionation = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + ConfigurationManager.AppSettings["DestinationPath"].ToString();
string sFile = sDestionation + sFileName;
if (!System.IO.Directory.Exists(sDestionation))
{
System.IO.Directory.CreateDirectory(sDestionation);
}
StreamWriter oWriter = null;
if (!System.IO.File.Exists(sFile))
{
oWriter = File.CreateText(sFile);
}
else
{
oWriter = File.AppendText(sFile);
}
oWriter.WriteLine(DateTime.Now.ToString() + ": " + sLogInfo.Trim());
}
答案 0 :(得分:6)
StreamWriter是IDisposable个对象。你应该在使用后处理它。为此,您可以使用using
语句,如下所示:
public void CreateLog(string sLogInfo)
{
string sDestionation = null;
string sFileName = DateTime.Now.ToString("yyyyMMdd") + "_log.txt";
sDestionation = @"D:\Log\";
var sFile = sDestionation + sFileName;
if (!Directory.Exists(sDestionation))
{
Directory.CreateDirectory(sDestionation);
}
using (var oWriter = new StreamWriter(sFile, true))
oWriter.WriteLine(DateTime.Now + ": " + sLogInfo.Trim());
}
答案 1 :(得分:2)
使用File.AppendAllText代替您完成所有步骤(创建文件夹除外)。
否则你应该在完成后妥善处理作家,最好在同一个函数中使用Components.Insert(Components.IndexOf(SourceComp), DestComp);
Components.Remove(SourceComp);
:
using
答案 2 :(得分:2)
您的代码看起来很好,但是,我认为您应该在最后添加以下内容:
using(oWriter)
{
oWriter.WriteLine(DateTime.Now.ToString() + ": " + sLogInfo.Trim());
}
答案 3 :(得分:1)
你应该刷新(处理足够的)你的数据到代码末尾的文件中:
oWriter.Flush();
//Save (Clears all buffers for the current writer and causes any buffered data to be written to the underlying stream.)
oWriter.Dispose(); //Then free this resource
当Yuval提到查看C#的StreamWriter.cs类时,它确实在内部调用了Flush
方法。见这里:Reference