我正在处理的文件系统监视程序应用程序有问题。单个文件似乎运行良好,但多个文件或其中包含文件的文件夹似乎运行良好。
在下面的代码中,我调用IsFileReady确定文件是否已完成写入,然后再尝试将其复制到另一个文件夹。但是,当创建一个新文件夹且其中包含文件时,由于某种原因,该文件夹将挂起而不继续。
我认为是因为同时写入了多个文件,而我的代码仅引用了一个文件,但是我不确定如何更正此问题。
感谢您的协助,谢谢。
static void Init()
{
string directory = watch_path;
Program._watcher = new FileSystemWatcher(directory);
Program._watcher.Created +=
new FileSystemEventHandler(Program._watcher_Changed);
Program._watcher.EnableRaisingEvents = true;
Program._watcher.IncludeSubdirectories = true;
}
static void _watcher_Changed(object sender, FileSystemEventArgs e)
{
Console.WriteLine("CHANGED, NAME: " + e.Name);
Console.WriteLine("CHANGED, FULLPATH: " + e.FullPath);
try
{
Console.WriteLine("Checking If File Exists at copy location");
if (!File.Exists(copy_path + "\\" + e.Name))
{
Console.WriteLine("Waiting for File to complete write");
WaitForFile(e.FullPath);
Console.WriteLine("Copying file to remote folder");
File.Copy(e.FullPath, copy_path + "\\" + e.Name);
Console.WriteLine("Copy Completed writing to log");
error_handling("File Copy Completed : ", copy_path + "\\" + e.Name, e.FullPath);
}
else
{
Console.WriteLine("Copy Failed Writing to Log");
error_handling("File Copy Skipped, File exists at destination : ", copy_path + "\\" + e.Name, e.FullPath);
}
}
catch (Exception error)
{
Console.WriteLine("Copy process totally failed" + error.Message);
error_handling("File Copy Failed ", "Exception: " + error.Message, "00");
}
}
public static void WaitForFile(string filename)
{
while (!IsFileReady(filename)) { }
}
public static bool IsFileReady(string filename)
{
try
{
using (FileStream inputStream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.None))
return inputStream.Length > 0;
}
catch (Exception)
{
return false;
}
*编辑
当挂起时,似乎WaitForFile从未真正完成。复制单个文件时,它没有问题,但是我认为,当有多个文件时,它会以某种方式卡住,并且不会越过
WaitForFile(e.FullPath);
我故意钩住Created事件。此应用程序的用途是监视多个Web服务器之间需要相同的文件夹。同步过程需要与Web服务器负载平衡一样快。
对error_handling的调用仅是写入日志的功能,如下所示:
public static void error_handling(string message, string fileident, string source)
{
using (System.IO.StreamWriter myFile = new System.IO.StreamWriter(log_folder + "\\" + log_file, true))
{
string finalMessage = string.Format("{0}: {1} SOURCE: {3} - DEST: {2}", DateTime.Now, message, fileident, source, Environment.NewLine);
myFile.WriteLine(finalMessage);
myFile.Close();
}
}