我有用于备份主机文件的代码。当我运行代码时,我收到以下错误:
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!");
}
}
答案 0 :(得分:3)
为了解释我在评论中的意思,让我们“逐步”完成您的代码,并说明您获得异常的原因。下面的过程与将断点放入代码并使用 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始终以管理员身份运行。
有关调试和单步执行代码的更多信息,请访问here