使用 FileSavePicker 写入文件

发布于 2024-12-19 23:30:04 字数 3642 浏览 1 评论 0原文

我很难弄清楚这个错误的原因是什么。我在清单中添加了 FilePicker 功能,而且我并不想做任何疯狂的事情;只是尝试保存到“文档”文件夹中的子文件夹...

错误:“未处理的异常类型 mscorlib.dll 中发生“System.UnauthorizedAccessException”
附加信息:访问被拒绝。 (HRESULT 的异常: 0x80070005(E_ACCESSDENIED))”

我已确认我的用户帐户是管理员,并且它对文件夹和文件具有完全控制权。但我不确定我还可以尝试什么。

public void NewBTN_Click(object sender, RoutedEventArgs e)
{

    var mbox = new MessageDialog("Would you like to save changes before creating a new Note?", "Note+ Confirmation");

    UICommand YesBTN = new UICommand("Yes", new UICommandInvokedHandler(OnYesBTN));
    UICommand NoBTN = new UICommand("No", new UICommandInvokedHandler(OnNoBTN));

    mbox.Commands.Add(YesBTN);
    mbox.Commands.Add(NoBTN);

    mbox.DefaultCommandIndex = 1;
    mbox.ShowAsync().Start();
}

async void OnYesBTN(object command)
{
    this.Dispatcher.Invoke(Windows.UI.Core.CoreDispatcherPriority.Normal, (s, a) =>
        {
            // User clicked yes. Show File picker.
            HasPickedFile = true;

        }, this, null);

    if (HasPickedFile)
    {
        FileSavePicker savePicker = new FileSavePicker();
        savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
        // Dropdown of file types the user can save the file as
        savePicker.FileTypeChoices.Add("Cascading Stylesheet", new List<string>() { ".css" });
        savePicker.FileTypeChoices.Add("Hypertext Markup Language", new List<string>() { ".html" });
        savePicker.FileTypeChoices.Add("Plain Text", new List<string>() { ".txt" });
        // Default extension if the user does not select a choice explicitly from the dropdown
        savePicker.DefaultFileExtension = ".txt";
        // Default file name if the user does not type one in or select a file to replace
        savePicker.SuggestedFileName = "New Note";
        StorageFile savedItem = await savePicker.PickSaveFileAsync();

        if (null != savedItem)
        {
            // Application now has read/write access to the saved file
            StorageFolder sFolder = await StorageFolder.GetFolderFromPathAsync(savedItem.Path);

            try
            {
                StorageFile sFile = await sFolder.GetFileAsync(savedItem.FileName);
                IRandomAccessStream writeStream = await sFile.OpenAsync(FileAccessMode.ReadWrite);

                IOutputStream oStream = writeStream.GetOutputStreamAt(0);
                DataWriter dWriter = new DataWriter(oStream);
                dWriter.WriteString(Note.Text);

                await dWriter.StoreAsync();
                oStream.FlushAsync().Start();

                // Should've successfully written to the file that Windows FileSavePicker had created.
            }
            catch
            {
                var mbox = new MessageDialog("This file does not exist.", "Note+ Confirmation");

                UICommand OkBTN = new UICommand("Ok", new UICommandInvokedHandler(OnOkBTN));

                mbox.Commands.Add(OkBTN);

                mbox.DefaultCommandIndex = 1;
                mbox.ShowAsync().Start();
            }
        }
    }
}

public void OnOkBTN(object command)
{
    this.Dispatcher.Invoke(Windows.UI.Core.CoreDispatcherPriority.Normal, (s, a) =>
        {
            // Do something here.
        }, this, null);
}
public void OnNoBTN(object command)
{
    this.Dispatcher.Invoke(Windows.UI.Core.CoreDispatcherPriority.Normal, (s, a) =>
        {
            // Don't save changes. Just create a new blank Note.
            Note.Text = String.Empty;
        }, this, null);
}

我如何写入由文件保存选择器?

I'm having a little difficulty figuring out what the cause of this error is. I've added FilePicker capabilities in the Manifest, and it's not like I'm trying to do anything crazy; just trying to save to a sub folder within the Documents folder...

Error: "An unhandled exception of type
'System.UnauthorizedAccessException' occurred in mscorlib.dll
Additional information: Access is denied. (Exception from HRESULT:
0x80070005 (E_ACCESSDENIED))"

I have confirmed that my User Account is Admin and that it has Full Control over folders and files. But I'm not sure what else I can try.

public void NewBTN_Click(object sender, RoutedEventArgs e)
{

    var mbox = new MessageDialog("Would you like to save changes before creating a new Note?", "Note+ Confirmation");

    UICommand YesBTN = new UICommand("Yes", new UICommandInvokedHandler(OnYesBTN));
    UICommand NoBTN = new UICommand("No", new UICommandInvokedHandler(OnNoBTN));

    mbox.Commands.Add(YesBTN);
    mbox.Commands.Add(NoBTN);

    mbox.DefaultCommandIndex = 1;
    mbox.ShowAsync().Start();
}

async void OnYesBTN(object command)
{
    this.Dispatcher.Invoke(Windows.UI.Core.CoreDispatcherPriority.Normal, (s, a) =>
        {
            // User clicked yes. Show File picker.
            HasPickedFile = true;

        }, this, null);

    if (HasPickedFile)
    {
        FileSavePicker savePicker = new FileSavePicker();
        savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
        // Dropdown of file types the user can save the file as
        savePicker.FileTypeChoices.Add("Cascading Stylesheet", new List<string>() { ".css" });
        savePicker.FileTypeChoices.Add("Hypertext Markup Language", new List<string>() { ".html" });
        savePicker.FileTypeChoices.Add("Plain Text", new List<string>() { ".txt" });
        // Default extension if the user does not select a choice explicitly from the dropdown
        savePicker.DefaultFileExtension = ".txt";
        // Default file name if the user does not type one in or select a file to replace
        savePicker.SuggestedFileName = "New Note";
        StorageFile savedItem = await savePicker.PickSaveFileAsync();

        if (null != savedItem)
        {
            // Application now has read/write access to the saved file
            StorageFolder sFolder = await StorageFolder.GetFolderFromPathAsync(savedItem.Path);

            try
            {
                StorageFile sFile = await sFolder.GetFileAsync(savedItem.FileName);
                IRandomAccessStream writeStream = await sFile.OpenAsync(FileAccessMode.ReadWrite);

                IOutputStream oStream = writeStream.GetOutputStreamAt(0);
                DataWriter dWriter = new DataWriter(oStream);
                dWriter.WriteString(Note.Text);

                await dWriter.StoreAsync();
                oStream.FlushAsync().Start();

                // Should've successfully written to the file that Windows FileSavePicker had created.
            }
            catch
            {
                var mbox = new MessageDialog("This file does not exist.", "Note+ Confirmation");

                UICommand OkBTN = new UICommand("Ok", new UICommandInvokedHandler(OnOkBTN));

                mbox.Commands.Add(OkBTN);

                mbox.DefaultCommandIndex = 1;
                mbox.ShowAsync().Start();
            }
        }
    }
}

public void OnOkBTN(object command)
{
    this.Dispatcher.Invoke(Windows.UI.Core.CoreDispatcherPriority.Normal, (s, a) =>
        {
            // Do something here.
        }, this, null);
}
public void OnNoBTN(object command)
{
    this.Dispatcher.Invoke(Windows.UI.Core.CoreDispatcherPriority.Normal, (s, a) =>
        {
            // Don't save changes. Just create a new blank Note.
            Note.Text = String.Empty;
        }, this, null);
}

How can I write to a file that was created by the FileSavePicker?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

川水往事 2024-12-26 23:30:04

您不需要调用 StorageFolder.GetFolderFromPathAsync(savedItem.Path)sFolder.GetFileAsync(savedItem.FileName)。您必须删除这两行,因为它们会引发异常。
您应该使用 savePicker.PickSaveFileAsync() 方法返回的 StorageFile 对象,因为该对象具有所有权限。然后您只需调用 savedItem.OpenAsync(FileAccessMode.ReadWrite) 即可。

You don't need to call StorageFolder.GetFolderFromPathAsync(savedItem.Path) and sFolder.GetFileAsync(savedItem.FileName). You must remove these two lines because they throw exception.
You should use the StorageFile object which has been returned by method savePicker.PickSaveFileAsync(), because that object has all permissions. Then you can simply call savedItem.OpenAsync(FileAccessMode.ReadWrite).

蓝海似她心 2024-12-26 23:30:04

您可能没有在应用程序的 appxmanifest 的功能部分中启用“文档库访问”。如果没有此功能,Windows 将限制对文件系统的访问。音乐、视频和图片库也有类似的功能。

您已经将“文件选择器”添加到声明部分,这可能不是您想要的。 “文件选择器”声明表明,如果其他应用程序调用文件选择器,您的应用程序将被列为可能的文件源。

You probably do not have "Document Library Access" enabled in the capabilities portion of the appxmanifest of your app. Without this capability, windows will restrict access to the file system. There are similar capabilities for music, video, and picture libraries.

You have already added "File Picker" to the declarations portion, which is probably not what you want. The "File Picker" declaration indicates that if some other application invokes the file picker, your app will be listed as a possible source of files.

老旧海报 2024-12-26 23:30:04

我还发现,在Manifest中添加视频或图片库访问功能只有在重新启动Windows 10后才会生效。
也许这是我电脑的问题,但我认为值得分享。

I've also found that adding Video or Picture Libraries access capability in Manifest only takes effect after restarting Windows 10.
Maybe it is an issue with my computer, but I think it is worth to share.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文