你如何检查写入权限的目录或文件? [英] How do you check for permissions to write to a directory or file?

查看:186
本文介绍了你如何检查写入权限的目录或文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序,使用类似下面的方法的一些数据写入到文件中。

I got a program that writes some data to a file using a method like the one below.


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);


     }
}

运行程序时,我得到一个错误:

When running the program I get an error:

未处理的异常信息:System.UnauthorizedAccessException:访问路径'mypath中被拒绝。      在System.IO .__ Error.WinIOError(的Int32错误code,字符串maybeFullPath)      在System.IO.FileStream.Init(字符串路径,的FileMode模式,FileAccess的访问,   NT32权利,布尔useRights,文件共享份额,的Int32缓冲区大小,FileOptions   ptions,SECURITY_ATTRIBUTES secAttrs,串MSGPATH,布尔bFromProxy)      在System.IO.FileStream..ctor(字符串路径,的FileMode模式,FileAccess的访问   文件共享份额,的Int32缓冲区大小,FileOptions选项,字符串MSGPATH,Boolea   bFromProxy)

Unhandled Exception: System.UnauthorizedAccessException: Access to the path 'mypath' is denied. at 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, String msgPath, Boolean bFromProxy) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolea bFromProxy)

问:code,我需要赶上这一点,如何授权的访问

Question: What code do I need to catch this and how do I grant the access?

推荐答案

更新:

此基础上改装这个答案中的code摆脱过时的方法。

Modified the code based on this answer to get rid of obsolete methods.

您可以使用安全命名空间进行检查:

You can use the Security namespace to check this:

public void ExportToFile(string filename)
{
    var permissionSet = new PermissionSet(PermissionState.None);    
    var writePermission = new FileIOPermission(FileIOPermissionAccess.Write, filename);
    permissionSet.AddPermission(writePermission);

    if (permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet))
    {
        using (FileStream fstream = new FileStream(filename, FileMode.Create))
        using (TextWriter writer = new StreamWriter(fstream))
        {
            // try catch block for write permissions 
            writer.WriteLine("sometext");


        }
    }
    else
    {
        //perform some recovery action here
    }

}

据得到这些权限,你将不得不要求用户为你做的某种方式。如果你可以编程方式做到这一点,那么我们都会有麻烦;)

As far as getting those permission, you are going to have to ask the user to do that for you somehow. If you could programatically do this, then we would all be in trouble ;)

这篇关于你如何检查写入权限的目录或文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆