不能用c#在txt文件上写文本

本文关键字:文本 文件 txt 不能 | 更新日期: 2023-09-27 18:07:12

我试图在文本文件上写一个字符串,但它没有写任何东西,也没有例外。我的代码是:

 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());
 }

不能用c#在txt文件上写文本

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());
    }

使用文件。AppendAllText,它将为您执行所有步骤(除了创建文件夹)。

否则,您应该在完成后正确地处置writer,最好在同一函数中使用using:

using(oWriter)
{
  oWriter.WriteLine(DateTime.Now.ToString() + ": " + sLogInfo.Trim());
}

你的代码看起来很好,但是,我认为你应该在它的末尾添加以下内容:oWriter.Close()

你应该刷新(处理就足够了)你的数据到你的代码末尾的文件: 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方法。参考资料