C# 无法使用C在txt文件上写入文本#
我试着在文本文件上写一个字符串,但它什么也不写,也没有例外。我的代码是:C# 无法使用C在txt文件上写入文本#,c#,winforms,C#,Winforms,我试着在文本文件上写一个字符串,但它什么也不写,也没有例外。我的代码是: public void CreateLog(string sLogInfo) { string sDestionation = null; string sFileName = DateTime.Now.ToString("yyyyMMdd") + "_log.txt"; sDestionation = @"D:\Log\"; //sDestionation = System.IO.P
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());
}
这就是目标。使用后应进行处理。为此,您可以使用如下语句:
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());
}
您应该在代码末尾将数据刷新(处理就足够了)到文件中:
oWriter.Flush()
//保存(清除当前写入程序的所有缓冲区,并将所有缓冲数据写入基础流)。
正如Yuval提到的,查看C#的StreamWriter.cs类时,它确实在内部调用了Flush
方法。请参见此处:使用它将为您完成所有步骤(创建文件夹除外)
否则,完成后应正确处理writer,最好在相同功能中使用:
using(oWriter)
{
oWriter.WriteLine(DateTime.Now.ToString() + ": " + sLogInfo.Trim());
}
您的代码看起来不错,但是,我认为您应该在代码末尾添加以下内容:
oWriter.Close()?我看不出有什么理由不能自己解决这个问题,或者至少可以通过调试进一步解决这个问题。看起来您被卡住了,因为您在进行任何调试之前停止了尝试。够了。它将在内部调用Flush
。
using(oWriter)
{
oWriter.WriteLine(DateTime.Now.ToString() + ": " + sLogInfo.Trim());
}