对于使用.NET进行安装,我希望使用cacls.exe授予文件夹中特定文件的写许可权,因此我引用了How to give Read/Write permissions to a Folder during installation using .NET,并使用了Setting File or Directory permissions ACE entries with .NET using CACLS.EXE中的代码。 安装后,在窗体加载时,我可以读取文件 file.txt ,它位于C:\ Program Files \ MyCompany \ MyProduct中,并带有以下代码:
private void Form1_Load(object sender, EventArgs e)
{
//Some code
DirectoryPermission dp = new
DirectoryPermission(filename, "Everyone", "F");
dp.SetAce();
foffset = read_file();
}
string filename = "file.txt";
private double read_file()
{
double value = 0;
try
{
value = Double.Parse(System.IO.File.ReadAllText(@filename));
return value;
}
catch
{
System.IO.File.WriteAllText(@filename, value.ToString());
return 0;
}
}
但是在单击按钮时,我无法用新值写入文件,因此我编写了以下代码并进行了安装,但问题仍然存在:
private void button1_Click(object sender, EventArgs e)
{
try{
DirectoryPermission dp = new
DirectoryPermission(filename , "Everyone", "F");
dp.SetAce();
System.IO.File.WriteAllText(@filename , offset.ToString());
}
catch
{}
}
我将完全控制所有用户,但无法写入该文件。而我得到这个错误
Exception thrown: 'System.UnauthorizedAccessException' in mscorlib.dll
请帮助我。