我在C#中有一个桌面应用程序,它将数据存储在 XML 文件中。 当应用程序安装在“Program Files”文件夹中时,其 XML 文件将转到 AppData(CommonApplicationData)文件夹中的文件夹。从这些文件中读取时没有问题,但在写入时会进入异常访问被拒绝的路径。当文件位于C:驱动器中安装了Windows的驱动器以外的其他驱动器时,读写没有问题。
下面是一个使目标路径具有完全控制权限的类:
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;
}
现在使用上面的类(CommonApplicationData)我制作了目标路径:
string _word, _path = new CommonApplicationData("Katek", "RemindWord", true).ToString() + @"\Words.xml", _description;
用户如何写入文件?
答案 0 :(得分:0)
问题在于文件属性(隐藏),我隐藏了文件,以防止用户意外删除它(因为它就像应用程序的数据库文件一样所以一个关键的文件)但是当它不被隐藏时,对文件的读写没有问题。 感谢您的所有贡献。