ako February 2016

access denied error when writing into a file in appData folder using c#

I have a desktop app in C# that stores it's data in an XML file. When application is installed in "Program Files" folder, its XML file goes to a folder in AppData(CommonApplicationData) folder. When reading from this files there is no problem but when writing into it it goes into exception access to the path denied. There is no problem with read and write when file is in a different drive other than C: Drive where windows is installed in.

Below is a class that makes target path with full control permission:

 public string ApplicationFolderPath
{
    get { return Path.Combine(CompanyFolderPath, applicationFolder); }
}
/// <summary>
/// Gets the path of the company's data folder.
/// </summary>
public string CompanyFolderPath
{
    get { return Path.Combine(directory, companyFolder); }
}


private string applicationFolder;
private string companyFolder;
private static readonly string directory =
    Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);

private void CreateFolders(bool allUsers)
{
    DirectoryInfo directoryInfo;
    DirectorySecurity directorySecurity;
    AccessRule rule;
    SecurityIdentifier securityIdentifier = new SecurityIdentifier
        (WellKnownSidType.BuiltinUsersSid, null);
    if (!Directory.Exists(CompanyFolderPath))
    {
        directoryInfo = Directory.CreateDirectory(CompanyFolderPath);
        bool modified;
        directorySecurity = directoryInfo.GetAccessControl();
        MessageBox.Show(directory.ToString());
        rule = new FileSystemAccessRule(
                securityIdentifier,
                FileSystemRights.FullControl,
                AccessControlType.Allow);
        directorySecurity.ModifyAccessRule(AccessControlModification.Add, rule, out modified);
        directoryInfo.SetAccessControl(directorySecurity);
    }
    if (!Directory.Exists(ApplicationFolderPath))
    {
        dir        

Answers


ako February 2016

the problem was with the file attribute ( hidden ) , i had made the file hidden in order to prevent users form removing it accidentally ( because it's like database file for the app and so a crucial file ) but when made it not to be hidden there is no problem with read and write on the file. thanks for all of your contributions .

Post Status

Asked in February 2016
Viewed 2,689 times
Voted 11
Answered 1 times

Search




Leave an answer