为了账号安全,请及时绑定邮箱和手机立即绑定

如何检查写入目录或文件的权限?

如何检查写入目录或文件的权限?

人到中年有点甜 2019-08-17 16:24:39
如何检查写入目录或文件的权限?我有一个程序,使用如下所示的方法将一些数据写入文件。public void ExportToFile(string filename){      using(FileStream fstream = new FileStream(filename,FileMode.Create))      using (TextWriter writer = new StreamWriter(fstream))      {          // try catch block for write permissions           writer.WriteLine(text);      }}运行程序时出现错误:未处理的异常:System.UnauthorizedAccessException:拒绝访问路径'mypath'。在System.IO .__ Error.WinIOError(Int32 errorCode,String maybeFullPath)at System.IO.FileStream.Init(String path,FileMode mode,FileAccess access,nt32 rights,Boolean useRights,FileShare share,Int32 bufferSize,FileOptions ptions,SECURITY_ATTRIBUTES secAttrs) System.IO.FileStream..ctor中的String String msgPath,Boolean bFromProxy(字符串路径,FileMode模式,FileAccess访问FileShare共享,Int32 bufferSize,FileOptions选项,字符串msgPath,Boolea bFromProxy)问题:我需要使用哪些代码来获取此信息以及如何授予访问权限?
查看完整描述

3 回答

?
浮云间

TA贡献1829条经验 获得超3个赞

当您的代码执行以下操作时:

  1. 检查当前用户是否有权执行某些操作。

  2. 执行需要检查1中的权利的操作。

您存在权限在12之间变化的风险,因为您无法预测在运行时系统上还会发生什么。因此,即使您之前已经检查过权限,您的代码也应该处理抛出UnauthorisedAccessException的情况。

请注意,SecurityManager类用于检查CAS权限,并且实际上不会检查当前用户是否具有对指定位置的写访问权(通过ACL和ACE)。因此,对于本地运行的应用程序,IsGranted将始终返回true。

示例

//1. Provide early notification that the user does not have permission to write.FileIOPermission writePermission = new FileIOPermission(FileIOPermissionAccess.Write, filename);if(!SecurityManager.IsGranted(writePermission)){
    //No permission. 
    //Either throw an exception so this can be handled by a calling function
    //or inform the user that they do not have permission to write to the folder and return.}//2. Attempt the action but handle permission changes.try{
    using (FileStream fstream = new FileStream(filename, FileMode.Create))
    using (TextWriter writer = new StreamWriter(fstream))
    {
        writer.WriteLine("sometext");
    }}catch (UnauthorizedAccessException ex){
    //No permission. 
    //Either throw an exception so this can be handled by a calling function
    //or inform the user that they do not have permission to write to the folder and return.}

这很棘手,不建议尝试以编程方式根据原始ACL(通过System.Security.AccessControl类提供的所有内容)从文件夹中计算有效权限。


查看完整回答
反对 回复 2019-08-17
  • 3 回答
  • 0 关注
  • 1098 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信