在我的.NET 2.0应用程序中,我需要检查是否有足够的权限来创建和写入目录的文件.为此,我有以下函数尝试创建一个文件并向其写入一个字节,然后删除自己以测试权限是否存在.
我认为检查的最佳方法是实际尝试并执行此操作,捕获发生的任何异常.虽然我对一般的异常捕获并不是特别高兴,所以有更好的或者更可接受的方式吗?
private const string TEMP_FILE = "\\tempFile.tmp";
/// <summary>
/// Checks the ability to create and write to a file in the supplied directory.
/// </summary>
/// <param name="directory">String representing the directory path to check.</param>
/// <returns>True if successful; otherwise false.</returns>
private static bool CheckDirectoryAccess(string directory)
{
bool success = false;
string fullPath = directory + TEMP_FILE;
if (Directory.Exists(directory))
{
try
{
using (FileStream fs = new FileStream(fullPath, FileMode.CreateNew,
FileAccess.Write))
{
fs.WriteByte(0xff);
}
if (File.Exists(fullPath))
{
File.Delete(fullPath);
success …Run Code Online (Sandbox Code Playgroud) 我FileIOPermission在.NET 3.5中尝试使用Windows 7.我一直是Windows XP用户,并且因为我是管理员而被授予此权限
我编写了以下代码,测试是否可以写入C:\ Program Files\Outlook ......
static void Main(string[] args)
{
Console.WriteLine("Am I an administrator? " + new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator);
// Try and open a file in C:\Program Files\Microsoft Office\Office14\BCSLaunch.dll
string path = @"C:\Program Files\Microsoft Office\Office14\BCSLaunch.dll";
try
{
FileIOPermission ioPerm = new FileIOPermission(FileIOPermissionAccess.Read, path);
ioPerm.Demand();
string backupPath = Path.ChangeExtension(path, ".bak");
FileIOPermission writeAccess = new FileIOPermission(FileIOPermissionAccess.AllAccess, backupPath);
writeAccess.Demand();
Console.WriteLine("Read access is permitted: {0} => {1}",path,SecurityManager.IsGranted(ioPerm));
Console.WriteLine("Write backup file is permitted: {0} => {1}", backupPath, SecurityManager.IsGranted(writeAccess));
File.Copy(path, backupPath);
Console.WriteLine("File …Run Code Online (Sandbox Code Playgroud)