使用c#写入appData文件夹中的文件时出现拒绝访问错误

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

我有一个用 C# 编写的桌面应用程序,它将其数据存储在 XML 文件中。 当应用程序安装在 "Program Files" 文件夹中时,其 XML 文件将转到 AppData(CommonApplicationData) 文件夹中的文件夹。当从这个文件中读取时没有问题,但是当写入它时它会进入异常访问路径被拒绝。 windows安装在C盘以外的其他盘读写没有问题。

下面是class使目标路径具有完全控制权限:

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

现在在这里使用上面的 class (CommonApplicationData) 我将目标路径设置为:

        string _word, _path = new CommonApplicationData("Katek", "RemindWord", true).ToString() + @"\Words.xml", _description;

但是当插入 Words.xml 文件时,它给了我这个异常

用户如何写入文件?

问题出在文件属性 ( hidden ) 上,我隐藏了文件以防止用户意外删除它(因为它就像应用程序的数据库文件所以一个关键文件)但是当它不被隐藏时,文件的读写没有问题。 感谢您的所有贡献。