在互联网上搜索,我找到了两种方法来确定进程是否可以写入文件;检查权限并尝试写入。我决定尝试这两个,并得出一个令人惊讶的结果。
检查文件的安全权限似乎报告该进程对受UAC保护的目录中的文件具有写访问权限,无论该进程是否以提升模式运行。另一方面,使用尝试写入(System.IO),仅当进程在提升模式下运行时,才会报告该进程对受UAC保护的目录中的文件具有写访问权。
我的问题如下:
以下是我用于测试的代码。
using System;
using System.IO;
using System.Security;
using System.Security.Permissions;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
foreach (var filename in new[]{@"C:\Windows\win.ini",
Environment.ExpandEnvironmentVariables(@"%tmp%\temp.txt")})
{
Console.WriteLine("File Name: {0}", filename);
Console.WriteLine("Write Permission : {0}", WriteAccess(filename));
Console.WriteLine("IO Write Attempt : {0}", WriteAccess2(filename));
Console.WriteLine();
}
var principal = System.Threading.Thread.CurrentPrincipal;
Console.ReadLine();
}
static bool WriteAccess(string filename)
{
var permissionSet = new PermissionSet(PermissionState.None);
permissionSet.AddPermission(new FileIOPermission(FileIOPermissionAccess.Write, filename));
return permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet);
}
static bool WriteAccess2(string filename)
{
try
{
// assumes the file exists
using (var fs = new FileStream(filename, FileMode.Open, FileAccess.ReadWrite))
return true;
}
catch (UnauthorizedAccessException)
{
return false;
}
}
}
}
输出(非提升过程)
File Name: C:\Windows\win.ini Write Permission : True IO Write Attempt : False File Name: C:\Users\Alex\AppData\Local\Temp\temp.txt Write Permission : True IO Write Attempt : True
输出(提升过程)
File Name: C:\Windows\win.ini Write Permission : True IO Write Attempt : True File Name: C:\Users\Alex\AppData\Local\Temp\temp.txt Write Permission : True IO Write Attempt : True