我正在尝试创建一个服务,尝试创建一个监控文件夹的服务。每当创建一个新文件时,我都会尝试在新位置读取新文件的内容并复制内容(使用相同的文件)。
我面临的问题是,只有第一个文件被复制并且文件在新位置创建,但没有任何内容。根本没有创建后续文件。
我的Services.cs看起来像这样: -
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
FileSystemWatcher Watcher = new FileSystemWatcher();
Watcher.Path = "C:\\logs\\";
Watcher.IncludeSubdirectories = true;
Watcher.Created += new FileSystemEventHandler(Watcher_Changed);
Watcher.EnableRaisingEvents = true;
}
private static void Watcher_Changed(object sender, FileSystemEventArgs e)
{
var CopyContents = new Thread(() => ThreadProcedure(e));
CopyContents.IsBackground = true;
CopyContents.Start();
}
private static void ThreadProcedure(FileSystemEventArgs e)
{
int counter = 0;
string line;
// Read the file and display it line by line.
System.IO.StreamReader file =
new System.IO.StreamReader(e.FullPath);
string testfilepath = "C:\\Project Tests\\testfile\\" + e.Name;
File.Create(testfilepath);
var log = new StreamWriter(testfilepath);
while ((line = file.ReadLine()) != null)
{
log.WriteLine(line);
counter++;
}
log.Close();
file.Close();
}
protected override void OnStop()
{
}
}