C#将文本输出到新行的文件

时间:2011-05-20 19:37:28

标签: c# .net windows

我有一些代码从FileSystemWatcher类输出数据,虽然每次输出一行到test.txt,它会覆盖前一个条目,有没有办法阻止这种情况发生?

有问题的代码:

static void FileWatcher_Created(object sender, FileSystemEventArgs e)
{

    using (StreamWriter fileWriter = new StreamWriter("test3.txt"))
    {
        var data = true;
        fileWriter.Write("C:\\" + e.Name + Environment.NewLine);
    }

完整代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace FileWatcherr
{
class Program
{    
    static void Main(string[] args)
    {
        string dirPath = "C:\\";
        FileSystemWatcher fileWatcher = new FileSystemWatcher(dirPath); 
        fileWatcher.IncludeSubdirectories = true;  
        fileWatcher.Filter = "*.exe";    
        // fileWatcher.Filter = "C:\\$Recycle.Bin";   
        //  fileWatcher.Changed += new FileSystemEventHandler(FileWatcher_Changed);   
        fileWatcher.Created += new FileSystemEventHandler(FileWatcher_Created);    
        //  fileWatcher.Deleted += new FileSystemEventHandler(FileWatcher_Deleted);  
        //  fileWatcher.Renamed += new RenamedEventHandler(FileWatcher_Renamed);    
        fileWatcher.EnableRaisingEvents = true;      

        // updated code


        Console.ReadKey(); 
    }



        static void FileWatcher_Renamed(object sender, RenamedEventArgs e)
        {
            Console.WriteLine(e.OldName + " was renamed to " + e.Name);
        }

        static void FileWatcher_Deleted(object sender, FileSystemEventArgs e)

        {
            Console.WriteLine(e.Name + " was deleted");
        }

        static void FileWatcher_Created(object sender, FileSystemEventArgs e)
        {

            using (StreamWriter fileWriter = new StreamWriter("test3.txt"))
            {
                var data = true;
                fileWriter.Write("C:\\" + e.Name + Environment.NewLine);
            }

        }

        static void FileWatcher_Changed(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine(e.Name + "");
        }
    }
}

5 个答案:

答案 0 :(得分:3)

编辑您的代码如下。 StreamWriter的第二个参数是我们是否应该追加或覆盖。设置为true表示追加,false表示覆盖(默认为问题)

   using (StreamWriter fileWriter = new StreamWriter("test3.txt", true))
    {
        var data = true;
        fileWriter.WriteLine(Path.Combine("C:\\", e.Name));
    }

有关此构造函数的更多信息,请访问http://msdn.microsoft.com/en-us/library/36b035cb.aspx

答案 1 :(得分:0)

考虑打开要附加的文件:

    using (StreamWriter fileWriter = new StreamWriter("test3.txt", true))
    {
        var data = true;
        fileWriter.WriteLine("C:\\" + e.Name);
    }

请注意,最好使用WriteLine方法。

答案 2 :(得分:0)

尝试

using (StreamWriter fileWriter = new StreamWriter("test3.txt", true))
{
...
}

答案 3 :(得分:0)

替换

new StreamWriter("test3.txt")

通过

new StreamWriter("test3.txt", true)

这将使流附加到文件。

答案 4 :(得分:0)

StreamWriter类有一个重载构造函数,它接受第二个bool参数,该参数指定是否要追加到现有文件。 More information here.