我的程序有没有权限在一个目录中创建文件,我该如何找出来?

4
如果我有在程序目录创建新文件的权限,我想要在那里创建该文件,如果没有,我想要在程序的AppData文件夹中创建该文件。
2个回答

7
你可以使用 FileIOPermission 来确定你的应用程序是否对文件/文件夹拥有特定权限。
来自 MSDN 的说明:
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
}

weiqure没有说他是否在Windows上使用c# - 但我不知道这一点。 - ChrisF
是的,我删除了我的 Try-Catch 答案。 - Dead account
我不太理解这个。如果我在C:\Windows中运行这段代码,它不会报错吗? - weiqure
如果你将可执行文件复制到c:\windows中,那么你必须拥有对其的写入权限吗? - PaulB
我用另一个账户将它复制到那里。 - weiqure
显示剩余2条评论

1

尝试创建文件夹并捕获随后的异常:其他任何操作都不安全,因为Windows是(或多或少)实时系统,在您测试权限和创建文件夹之间,权限可能已更改。考虑以下潜在的关键事件链:

  • 用户即将更改文件夹权限
  • 应用程序测试文件夹创建权限:测试权限成功
  • 用户提交更改
  • 应用程序尝试创建文件夹

请不要未经说明理由就给我点踩。我怎么知道我的帖子哪里出了问题? - Konrad Rudolph
我暂时会使用这种方法,尽管我并不喜欢它。 - weiqure
@null:如果这能让你感到安慰,我也不喜欢它。 - Konrad Rudolph

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接