写入文本文件时缺少某些内容

本文关键字:文本 文件 | 更新日期: 2023-09-27 17:53:39

我只是希望能够将某些文件的路径记录到文本文件中。我有以下命令来做日志记录。

static void LogFile(string lockedFilePath)
    {
        Assembly ass = Assembly.GetExecutingAssembly();
        string workingFolder = System.IO.Path.GetDirectoryName(ass.Location);
        string LogFile = System.IO.Path.Combine(workingFolder, "logFiles.txt");
        if (!System.IO.File.Exists(LogFile))
        {
            using (System.IO.FileStream fs = System.IO.File.Create(LogFile))
            {
                using (System.IO.StreamWriter sw = new StreamWriter(fs))
                {
                    sw.WriteLine(lockedFilePath);   
                }
            }
        }
        else
        {
            using (System.IO.FileStream fs = System.IO.File.OpenWrite(LogFile))
            {
                using (System.IO.StreamWriter sw = new StreamWriter(fs))
                {
                    sw.WriteLine(lockedFilePath);
                }
            }
        }
    }

但是如果我在控制台应用程序中像这样调用它

foreach (string f in System.IO.Directory.GetFiles(@"C:'AASource"))
            {
                Console.WriteLine("Logging : " + f);
                LogFile(f);
            }
            Console.ReadLine();

结果文本文件中列出的唯一文件是dir中的最后一个文件。我做错了什么?

写入文本文件时缺少某些内容

System.IO.File.AppendText(LogFile)代替System.IO.File.OpenWrite(LogFile)。当你使用OpenWrite时,你将用你所写的内容覆盖内容。

此外,您的if语句(if (!System.IO.File.Exists(LogFile)))是不需要的。如果该文件不存在,AppendText(和OpenWrite)将创建该文件。这意味着您可以简单地在else子句中运行代码。

您需要以追加模式打开文件。否则,将删除文件中以前的所有内容。

下面是我使用的日志文件代码,如果你想看一些其他的例子。

文件。追加文本MSDN

每次调用LogFile方法时都会重写文件。你可以使用重载的StreamWriter,它允许追加到文件的末尾:

void LogFile(string lockedFilePath)
{
    Assembly ass = Assembly.GetExecutingAssembly();
    string workingFolder = System.IO.Path.GetDirectoryName(ass.Location);
    string LogFile = System.IO.Path.Combine(workingFolder, "logFiles.txt");
    using (System.IO.StreamWriter sw = new StreamWriter(LogFile, true))
    {
        sw.WriteLine(lockedFilePath);   
    }
}
static void LogFile(string lockedFilePath)
        {
            Assembly ass = Assembly.GetExecutingAssembly();
            string workingFolder = System.IO.Path.GetDirectoryName(ass.Location);
            string LogFile = System.IO.Path.Combine(workingFolder, "logFiles.txt");
            System.IO.File.AppendAllText(LogFile, System.Environment.NewLine + lockedFilePath);
        }

您应该刷新并关闭StreamWriter。如果只写最后一个文件,那么你只是覆盖了你所拥有的。

见到你