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

时间:2018-10-13 09:56:49

标签: c# visual-studio uwp file-permissions uwp-xaml

我正在开发一个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;
    }

1 个答案:

答案 0 :(得分:1)

FileSystemAccessRule属于System.Security.AccessControl命名空间,而uwp不是compatible。您无法使用它来访问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\Packages\497f6a93-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