代码之家  ›  专栏  ›  技术社区  ›  weiqure

如何确定我的程序是否有权在目录中创建文件?

  •  4
  • weiqure  · 技术社区  · 17 年前

    如果我有权在程序目录中创建新文件,我想在那里创建该文件,如果没有,我想在程序的AppData文件夹中创建该文件。

    2 回复  |  直到 17 年前
        1
  •  7
  •   PaulB    17 年前

    你可以用 FileIOPermission 以确定应用程序是否具有文件/文件夹的特定权限。

    FileIOPermission f = new FileIOPermission(PermissionState.None);
    f.AllLocalFiles = FileIOPermissionAccess.Read;
    try
    {
        f.Demand();
    }
    catch (SecurityException s)
    {
        Console.WriteLine(s.Message);
    }
    

    编辑:对您的问题更明确的回答可能是:

    private string GetWritableDirectory()
    {
      string currentDir = Environment.CurrentDirectory; // Get the current dir
      FileIOPermission f = new FileIOPermission(FileIOPermissionAccess.Write, currentDir);
      try
      {
        f.Demand(); // Check for write access
      }
      catch (SecurityException s)
      {
        return Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) ; // Return the appdata (you may want to pick a differenct folder here)
      }
      return currentDir; // Have write access to current dir
    }
    
        2
  •  1
  •   Konrad Rudolph    17 年前

    只需尝试创建文件夹并捕获随后出现的异常:其他所有内容都不安全,因为Windows(或多或少)是一个实时系统,在您测试权限和创建文件夹之间,权限可能已经更改。考虑以下潜在的、关键事件链:

    • 文件夹创建权限的应用程序测试:权限测试成功
    • 应用程序尝试创建文件夹
    推荐文章