[英](File.Copy) Unhandled 'System.IO.IOException' in mscorlib.dll
[英]File.Copy, An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll
我正在使用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循环中尝试更改的第一个文件上引发此错误。
我不确定是什么导致此错误。 如果我删除测试文件夹中的内容,然后启动程序,则不会发生该错误。
任何帮助,将不胜感激。 :)
File.Copy()
的第三个参数必须为true
以使其能够覆盖已存在的文件。
File.Copy(newPath, newPath.Replace(GamesDirectory, TestDirectory), true);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.