开发者

Intermittent UnauthorizedAccessException storing configuration files in CommonApplicationData

I've built an application which has a local configuration store under Environment.SpecialFolder.CommonApplicationData. (The store is per-machine because it reflects configuration changes in radio devices paired with the PC.) My installer is marked in the manifest to run as administrator, and creates the subdirectories with the following routine:

private static void CreateAndPermit(SecurityIdentifier securityIdentifier, String path)
{
    DirectoryInfo info = new DirectoryInfo(path);
    if (!info.Exists)
        info.Create();

    DirectorySecurity security = info.GetAccessControl();
    AccessRule rule = new FileSystemAccessRule(securityIdentifier,
            FileSystemRights.Write |
            FileSystemRights.ReadAndExecute |
            FileSystemRights.Modify |
            FileSystemRights.CreateFiles,
            InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
            PropagationFlags.InheritOnly,
            AccessControlType.Allow);
    bool modified;
    security.ModifyAccessRule(AccessControlModification.Add, rule, out modified);
    info.SetAccessControl(security);
}

This creates a directory that desktop users can access using Explorer, and where my application can write configuration data. My application code then a开发者_高级运维ttempts to update the configuration file with the following sequence (not using File.Replace as I've broken down the steps for debugging):

    if (File.Exists(filename + ".bak"))
        File.Delete(filename + ".bak");
    if (File.Exists(filename))
        File.Move(filename, filename + ".bak");
    File.Move(tmpfile, filename);

This code intermittently (and never on my development machine) throws System.UnauthorizedAccessException, generally on the step where it deletes the backup file. After the exception Explorer indicates that "Everyone" has permissions for everything except "Special Permissions".

The only clue I've had is that one end user experienced the problem after switching their XP Pro machine from standalone login to using a domain.


Such are the hazards of running code on a multi-tasking operating system, there's no guarantee that a file you open or use isn't also in use by another process. Think search indexers, virus scanners, toolbars. Or just plain another process that the user started to look at the file. Including another instance of your program.

Assuming such programs are uninterested in .bak files, one scenario where deleting the .bak file won't work is on the second time the user saves the file. Where some other process had a handle open on the original file. Renaming the file to .bak won't be a problem. Deleting it will.

Assume failure, catch IOException and tell the user it won't work right now. The user's IT staff know how to use, say, SysInternals' Handle utility to find out who's got the file locked.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜