使用FileSavePicker写入文件

时间:2011-12-06 17:20:33

标签: c# .net windows-runtime microsoft-metro .net-4.5

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

  

错误:“未处理的类型异常   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);
}

如何写入由FileSavePicker创建的文件?

3 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:2)

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

您已添加&#34;文件选择器&#34;到声明部分,这可能不是你想要的。 &#34;文件选择器&#34;声明表示如果某个其他应用程序调用文件选择器,您的应用程序将被列为可能的文件源。

答案 2 :(得分:0)

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