Unable to write file in using cacls.exe

77 Views Asked by At

For installation using .NET, I wish to give write permission to a particular file in the folder using cacls.exe, so I have referred How to give Read/Write permissions to a Folder during installation using .NET and I have used the code from Setting File or Directory permissions ACE entries with .NET using CACLS.EXE. After installation, on form load, I could read the file file.txt which is located at C:\Program Files\MyCompany\MyProduct , with below code:

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;
}
}

But on a button click I couldn't write the file with new value, so I wrote the below code and did installation, still the problem persist:

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
 {}
}

I'm giving full control to all the users, but I'm not able to write the file. and I'm getting this error

  Exception thrown: 'System.UnauthorizedAccessException' in mscorlib.dll

Please help me in this.

0

There are 0 best solutions below