设置访问权限在调试模式下有效,但在发布模式下无效

set access permission works in debug mode but not in release mode

我正在开发一个 UWP 软件,我需要在其中写入位于 Temp 目录中的 "input.txt" 文件。但是,当在发布模式下授予此目录权限时,我遇到了问题,并且看起来权限未设置:

        string str = inputmessage.Text;

        string path = @"input.txt";

        try
        {
            SetAccess(WindowsIdentity.GetCurrent().Name, 
            Path.GetTempPath());// Path.GetFullPath("."));

            // FileStream.SetAccessControl();
            File.WriteAllText(Path.GetTempPath()+path,str);
        }

并且设置访问权限定义为:

       private static bool SetAccess(string user, string folder)
    {
        const FileSystemRights Rights = FileSystemRights.FullControl;

        // *** Add Access Rule to the actual directory itself
        var AccessRule = new FileSystemAccessRule(user, Rights,
            InheritanceFlags.None,
            PropagationFlags.NoPropagateInherit,
            AccessControlType.Allow);

        var Info = new DirectoryInfo(folder);
        var Security = Info.GetAccessControl(AccessControlSections.Access);
        bool Result;

        Security.ModifyAccessRule(AccessControlModification.Set, AccessRule, out Result);

        if (!Result) return false;

        // *** Always allow objects to inherit on a directory
        const InheritanceFlags iFlags = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;

        // *** Add Access rule for the inheritance
        AccessRule = new FileSystemAccessRule(user, Rights,
            iFlags,
            PropagationFlags.InheritOnly,
            AccessControlType.Allow);

        Security.ModifyAccessRule(AccessControlModification.Add, AccessRule, out Result);

        if (!Result) return false;

        Info.SetAccessControl(Security);

        return true;
    }

FileSystemAccessRule is belong to System.Security.AccessControl Namespace, and it is not compatible with uwp. You could not use it to access TemporaryFolder.

如果要写入位于 Temp 目录中的 "input.txt" 文件。请参考以下流程。

private async void writeTextToTem(string info)
{
    var file = await ApplicationData.Current.TemporaryFolder.CreateFileAsync("info.text", CreationCollisionOption.OpenIfExists);

    if (file != null)
    {
        await Windows.Storage.FileIO.WriteTextAsync(file, info);
    }
}

Path.GetTempPath()也可以在uwp中使用,匹配的文件夹是 C:\Users\Administrator\AppData\Local\Packages7f6a93-9de3-4985-b27e-c2215ebabe72_75crXXXXXXX\AC\Temp\,它包含在应用程序的沙箱中,您可以直接访问它。

var path = Path.GetTempPath();
var folder = await StorageFolder.GetFolderFromPathAsync(path);
var file = await folder.CreateFileAsync("info.text", CreationCollisionOption.OpenIfExists);
if (file != null)
{
    await Windows.Storage.FileIO.WriteTextAsync(file, str);
}

详情请参考File access permissions