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))
{
directoryInfo = Directory.CreateDirectory(ApplicationFolderPath);
if (allUsers)
{
bool modified;
directorySecurity = directoryInfo.GetAccessControl();
rule = new FileSystemAccessRule(
securityIdentifier,
FileSystemRights.Write |
FileSystemRights.ReadAndExecute |
FileSystemRights.Modify,
InheritanceFlags.ContainerInherit |
InheritanceFlags.ObjectInherit,
PropagationFlags.InheritOnly,
AccessControlType.Allow);
directorySecurity.ModifyAccessRule(AccessControlModification.Add, rule, out modified);
directoryInfo.SetAccessControl(directorySecurity);
}
}
}
/// <summary>
/// Returns the path of the application's data folder.
/// </summary>
/// <returns>The path of the application's data folder.</returns>
public override string ToString()
{
return ApplicationFolderPath;
}
now here using the above class (CommonApplicationData) i make the target path:
string _word, _path = new CommonApplicationData("Katek", "RemindWord", true).ToString() + @"\Words.xml", _description;
but when inserting into the Words.xml file it gives me this exception
How can user write into the file?