我需要测试用户是否可以在实际尝试之前写入文件夹.
我已经实现了以下方法(在C#2.0中),它尝试使用Directory.GetAccessControl()方法检索文件夹的安全权限.
private bool hasWriteAccessToFolder(string folderPath)
{
try
{
// Attempt to get a list of security permissions from the folder.
// This will raise an exception if the path is read only or do not have access to view the permissions.
System.Security.AccessControl.DirectorySecurity ds = Directory.GetAccessControl(folderPath);
return true;
}
catch (UnauthorizedAccessException)
{
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
当我在谷歌搜索如何测试写入访问时,没有出现这样的情况,实际测试Windows中的权限似乎非常复杂.我担心我过度简化了事情并且这种方法并不健全,尽管它似乎确实有效.
我的方法是否可以测试当前用户是否具有写访问权限?
如果File.SetAttributes("C:\\myFile.txt", FileAttributes.ReadOnly);将文件设置为只读,如果需要,如何将其设置为读/写?
我怀疑它会FileAttributes.Normal改变文件的任何其他属性吗?MSDN网站上没有非常具有描述性的说明......
该文件是正常的,没有设置其他属性.仅当单独使用时,此属性才有效.
谢谢