写入文本文件时遗漏了某些内容

eto*_*bot 1 c#

我只是希望能够将某些文件的路径记录到文本文件中.我有以下内容来进行日志记录.

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);
                }
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

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

foreach (string f in System.IO.Directory.GetFiles(@"C:\AASource"))
            {
                Console.WriteLine("Logging : " + f);
                LogFile(f);
            }
            Console.ReadLine();
Run Code Online (Sandbox Code Playgroud)

生成的文本文件中列出的唯一文件是目录中的最后一个文件.我究竟做错了什么?

Rud*_*ser 5

而不是System.IO.File.OpenWrite(LogFile),使用System.IO.File.AppendText(LogFile).当你使用时,OpenWrite你将用你写的任何内容覆盖内容.

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