我正在使用Windows窗体的C#编写程序,该程序位于后台,并且需要监视对目录的更改并将这些更改自动复制到目标目录中。该程序还将在启动时检查两个目录之间是否有任何更改,并将其复制。理想情况下,此程序运行时,目标目录将是基本目录的副本。
这是我的代码。
private const string GamesDirectory = "D:\\Games";
private const string TestDirectory = "D:\\Test";
#region Fields
private readonly Process _launcher;
#endregion
#region Constructors
/// <summary>
/// Initialises an instance of the <see cref="GameReviewManager" /> class.
/// </summary>
public GameReviewManager()
{
InitializeComponent();
_launcher = new Process();
_launcher.StartInfo.FileName = "GameReviewLauncher";
_launcher.EnableRaisingEvents = true;
_launcher.Exited += LauncherExited;
_launcher.Start();
MonitorDirectory(TestDirectory);
}
#endregion
#region Private Methods
/// <summary>
/// Handles the launcher exited event.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The event.</param>
private void LauncherExited(object sender, EventArgs e)
{
_launcher.Start();
}
private static void MonitorDirectory(string path)
{
FileSystemWatcher fileSystemWatcher = new FileSystemWatcher();
fileSystemWatcher.Path = path;
fileSystemWatcher.Created += FileSystemWatcherCreated;
fileSystemWatcher.Renamed += FileSystemWatcherRenamed;
fileSystemWatcher.Deleted += FileSystemWatcherDeleted;
fileSystemWatcher.EnableRaisingEvents = true;
//Now Create all of the directories
foreach (string dirPath in Directory.GetDirectories(GamesDirectory, "*", SearchOption.AllDirectories))
{
Directory.CreateDirectory(dirPath.Replace(GamesDirectory, TestDirectory));
}
//Copy all the files & Replaces any files with the same name
foreach (string newPath in Directory.GetFiles(GamesDirectory, "*", SearchOption.AllDirectories))
{
File.Copy(newPath, newPath.Replace(GamesDirectory, TestDirectory), false);
}
}
private static void FileSystemWatcherCreated(object sender, FileSystemEventArgs e)
{
Console.WriteLine("File created: {0}", e.Name);
}
private static void FileSystemWatcherRenamed(object sender, FileSystemEventArgs e)
{
Console.WriteLine("File renamed: {0}", e.Name);
}
private static void FileSystemWatcherDeleted(object sender, FileSystemEventArgs e)
{
Console.WriteLine("File deleted: {0}", e.Name);
}
#endregion
}
运行程序时出现此错误,mscorlib.dll中发生了'System.IO.IOException'类型的未处理异常
它在MonitorDirectory方法的第二个foreach循环中尝试更改的第一个文件上引发此错误。
我不确定是什么原因导致此错误。如果我删除测试文件夹中的内容,然后启动程序,则不会发生错误。
任何帮助将不胜感激。 :)
答案 0 :(得分:0)
true
的第三个参数必须为File.Copy(newPath, newPath.Replace(GamesDirectory, TestDirectory), true);
,以使其能够覆盖已存在的文件。
awk '/^instance-name-3 /{print $3}' your_file.txt