C# Output text to file on a new line
I have some code which outputs data from the FileSystemWatcher class, although each times to outputs a line to test.txt, it overwrites the previous entry, is there a way to stop this happening?
Code in question:
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);
}
Full Code:
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 + "");
}
}
}
Edit your code to be the below. The second parameter to the StreamWriter
is if we should append or overwrite. Set to true to append and false to overwrite (default, thus your problem)
using (StreamWriter fileWriter = new StreamWriter("test3.txt", true))
{
var data = true;
fileWriter.WriteLine(Path.Combine("C:\\", e.Name));
}
More info about this constructor can be found here http://msdn.microsoft.com/en-us/library/36b035cb.aspx
Try
using (StreamWriter fileWriter = new StreamWriter("test3.txt", true))
{
...
}
Replace
new StreamWriter("test3.txt")
by
new StreamWriter("test3.txt", true)
This will make the stream append to the file.
Consider opening file to append:
using (StreamWriter fileWriter = new StreamWriter("test3.txt", true))
{
var data = true;
fileWriter.WriteLine("C:\\" + e.Name);
}
Note that it is better to use WriteLine
method.
The StreamWriter class has an overload constructor that takes a second bool parameter which specifies if you want to append to an existing file. More information here.
精彩评论