这里是你能做什么:
1)如果您有权访问文件之前试图访问你的文件,你可以测试。从this SO thread,这里是一个方法,如果用户具有Write
权限(即右键单击文件 - >属性 - >安全性),应该返回true。这包括你的未分配访问权限点(2)(请注意,也可以是更强大的/防错得到这个信息比下面的代码):
public static bool HasWritePermissionOnFile(string path)
{
bool writeAllow = false;
bool writeDeny = false;
FileSecurity accessControlList = File.GetAccessControl(path);
if (accessControlList == null)
{
return false;
}
var accessRules = accessControlList.GetAccessRules(true, true, typeof(SecurityIdentifier));
if (accessRules == null)
{
return false;
}
foreach (FileSystemAccessRule rule in accessRules)
{
if ((FileSystemRights.Write & rule.FileSystemRights) != FileSystemRights.Write)
{
continue;
}
if (rule.AccessControlType == AccessControlType.Allow)
{
writeAllow = true;
}
else if (rule.AccessControlType == AccessControlType.Deny)
{
writeDeny = true;
}
}
return writeAllow && !writeDeny;
}
2)不要尝试实例您FileStream
和捕获异常:
try
{
string file = "...";
bool hasWritePermission = HasWritePermissionOnFile(file);
using (FileStream fs = new FileStream(file, FileMode.Open))
{
}
}
catch (UnauthorizedAccessException ex)
{
// Insert some logic here
}
catch (FileNotFoundException ex)
{
// Insert some logic here
}
catch (IOException ex)
{
// Insert some logic here
}
在你的情况(3)(文件需要提升),UnauthorizedAccessException
被抛出。
在你的情况(1)(文件被另一个进程锁定)时,会抛出IOException
。然后您可以检查异常的HRESULT以获取更多详细信息:
catch (IOException ex)
{
// Gets the HRESULT
int hresult = Marshal.GetHRForException(ex);
// See http://msdn.microsoft.com/en-us/library/windows/desktop/ms681382(v=vs.85).aspx
// for system error code
switch (hresult & 0x0000FFFF)
{
case 32: //ERROR_SHARING_VIOLATION
Console.WriteLine("File is in use by another process");
break;
}
}
现在您应该能够区分您的3个用例。
你想检查的最后2个案例有区别吗?我会想象(虽然没有证明)他们都会抛出一个'SecurityException',第一个案例会抛出一个'IOException'。 – 2012-02-21 00:49:22
@ M.Babcock:在某些方面,最后两种情况并没有很大的不同。但是,用户必须(通常)为了访问文件而做了非常不同的事情。对于第二种情况,他们可能需要请求其他用户授予他们许可。对于第三种情况,他们需要“以管理员身份运行”或者将文件移出“Program Files”目录(尽管为什么它会出现在我不知道的地方)。我想帮助用户知道他们需要做什么才能访问该文件。 – skybluecodeflier 2012-02-21 00:57:37
在我之前的评论中,我可能再次表现出我对Windows操作系统的无知 - 如果我的解释不正确,我愿意纠正。 – skybluecodeflier 2012-02-21 00:58:25