Skip to main content
 首页 » 编程设计

c#之写入文本文件时丢失某些内容

2024年02月23日16yxwkf

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

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

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

请您参考如下方法:

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

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