简体   繁体   English

对C#中的文件夹或UNC路径的写权限

[英]Write permissions on a folder or UNC path in c#

Any way to check if write permissions are available on a given path that could be either a local folder (c:\\temp) or a UNC (\\server\\share)? 有什么方法可以检查给定路径上的写权限是否可用,该路径可能是本地文件夹(c:\\ temp)或UNC(\\ server \\ share)? I can't use try/catch because I might have write permissions but not delete so I wouldn't be able to delete created file... 我无法使用try / catch,因为我可能具有写权限,但无法删除,因此无法删除创建的文件...

You use a permissions demand , thus: 您使用权限需求 ,因此:

FileIOPermission f2 = new FileIOPermission(FileIOPermissionAccess.Read, "C:\\test_r");
f2.AddPathList(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, "C:\\example\\out.txt");
try
{
  f2.Demand();
  // do something useful with the file here
}
catch (SecurityException s)
{
  Console.WriteLine(s.Message);
  // deal with the lack of permissions here.
}

specifying the permissions you want and the file system object(s) desired. 指定所需的权限和所需的文件系统对象。 If you don't have the demanded permission, a Security exception is thrown. 如果您没有所需的权限,则会引发Security异常。 More details at 有关更多详细信息,请访问

For a variety of reasons — race conditions being one of them — it's more complicated than it might seem to examine NTFS file system permissions. 由于种种原因(竞争条件就是其中之一),它比检查NTFS文件系统权限看起来要复杂得多。

Apparently, we figured out a while back that this is a no-op for UNC paths. 显然,我们不久前就发现这是UNC路径的禁忌之选。 See this question, Testing a UNC Path's "Accessability" , for detials. 有关详细信息,请参见测试UNC路径的“可访问性”这个问题。

A little google-fu suggests that this CodeProject class might be of use, though: http://www.codeproject.com/Articles/14402/Testing-File-Access-Rights-in-NET-2-0 一点Google-fu建议您使用此CodeProject类,不过: http : //www.codeproject.com/Articles/14402/Testing-File-Access-Rights-in-NET-2-0

Yes you can use the FileIOPermission class and the FileIOPermissionAccess enum. 是的,您可以使用FileIOPermission类和FileIOPermissionAccess枚举。

FileIOPermissionAccess.Write : FileIOPermissionAccess.Write

Access to write to or delete a file or directory. 可以写入或删除文件或目录。 Write access includes deleting and overwriting files or directories. 写访问包括删除和覆盖文件或目录。


FileIOPermission f = new FileIOPermission(FileIOPermissionAccess.Write, myPath);

try
{
   f.Demand();
   //permission to write/delete/overwrite
}
catch (SecurityException s)
{
   //there is no permission to write/delete/overwrite
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM