';System.UnauthorizedAccessException';但文件仍在复制中
本文关键字:复制 System UnauthorizedAccessException 文件 | 更新日期: 2023-09-27 18:01:08
我有一些代码要用来备份主机文件。当我运行代码时,我得到以下错误:
mscorlib.dll 中发生"System.UnauthorizedAccessException"类型的未处理异常
奇怪的是,文件正在被复制。我不确定代码指的是什么,因为如果异常本身没有被抛出,一切都会井然有序(或者看起来是这样(。
代码如下:
private void BackUpHost()
{
string fileName = "hosts";
string newFileName = "hosts.bak";
string sourcePath = @"c:'windows'system32'drivers'etc";
string targetPath = @"c:'windows'system32'drivers'etc";
string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
string destFile = System.IO.Path.Combine(targetPath, newFileName);
if (!System.IO.Directory.Exists(targetPath))
{
System.IO.Directory.CreateDirectory(targetPath);
}
System.IO.File.Copy(sourceFile, destFile, true);
if (System.IO.Directory.Exists(sourcePath))
{
fileName = System.IO.Path.GetFileName(sourcePath);
destFile = System.IO.Path.Combine(targetPath, newFileName);
System.IO.File.Copy(sourcePath, destFile, true);
}
else
{
Console.WriteLine("Source path does not exist!");
}
}
为了解释我在评论中的意思,让我们"逐步"了解您的代码,并显示您为什么会出现异常。下面的过程与将断点放入代码中并使用F10遍历每个断点并查看调试器窗口的"本地变量"部分的过程相同。
private void BackUpHost()
{
string fileName = "hosts";
string newFileName = "hosts.bak";
string sourcePath = @"c:'windows'system32'drivers'etc";
string targetPath = @"c:'windows'system32'drivers'etc";
string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
// sourceFile = "c:'windows'system32'drivers'etc'hosts"
string destFile = System.IO.Path.Combine(targetPath, newFileName);
// destFile = "c:'windows'system32'drivers'etc'hosts.bak"
if (!System.IO.Directory.Exists(targetPath))
{
System.IO.Directory.CreateDirectory(targetPath);
}
System.IO.File.Copy(sourceFile, destFile, true); // First File.Copy() call
// File "c:'windows'system32'drivers'etc'hosts.bak" is created as a
// copy of "c:'windows'system32'drivers'etc'hosts" if either UAC is
// disabled or the application is run as Administrator.
// Otherwise "UnauthorizedAccessException - Access to path denied" is thrown
if (System.IO.Directory.Exists(sourcePath))
{
fileName = System.IO.Path.GetFileName(sourcePath); // Setting of fileName is not used in your code again, is this intended or a mistake?
// fileName = "etc" (Since the value of sourcePath is "c:'windows'system32'drivers'etc", GetFileName() sees the "etc" part as the FileName.
// Should this not have been GetFileName(sourceFile) ??
destFile = System.IO.Path.Combine(targetPath, newFileName);
// destFile = "c:'windows'system32'drivers'etc'hosts.bak"
System.IO.File.Copy(sourcePath, destFile, true); // Second File.Copy() call
// This is where your exception happens since you are trying to copy
// the file "etc" (which is actually a folder)
}
else
{
Console.WriteLine("Source path does not exist!");
}
}
您之所以看到"hosts.bak"文件,是因为您执行了第一个File.Copy()
调用。由于正在创建该文件,我必须假设您在环境中禁用了UAC,或者您的Visual Studio始终以管理员身份运行。
有关调试和进入/跳过代码的更多信息,请访问