Pregunta

Tengo un poco de dificultad para descubrir cuál es la causa de este error. he añadido FilePicker capacidades en el manifiesto, y no es como si estuviera tratando de hacer algo loco; Solo trato de guardar en una subcoleta dentro de la carpeta de documentos ...

Error: "Una excepción no controlada del tipo 'System.UnAuthorizedAccessException' ocurrió en mscorlib.dll
Información adicional: se niega el acceso. (Excepción de HRESULT: 0x80070005 (E_ACCESSDENED) "

He confirmado que mi cuenta de usuario es administrador y que tiene control total sobre carpetas y archivos. Pero no estoy seguro de qué más puedo probar.

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);
}

¿Cómo puedo escribir en un archivo creado por FileSavePicker?

¿Fue útil?

Solución

No necesitas llamar StorageFolder.GetFolderFromPathAsync(savedItem.Path) y sFolder.GetFileAsync(savedItem.FileName). Debe eliminar estas dos líneas porque lanzan una excepción. Debe usar el objeto StorageFile que ha sido devuelto por método savePicker.PickSaveFileAsync(), porque ese objeto tiene todos los permisos. Entonces simplemente puedes llamar savedItem.OpenAsync(FileAccessMode.ReadWrite).

Otros consejos

Probablemente no tenga "acceso a la biblioteca de documentos" habilitado en la parte de capacidades del AppXManifest de su aplicación. Sin esta capacidad, Windows restringirá el acceso al sistema de archivos. Hay capacidades similares para la música, el video y las bibliotecas de imágenes.

Ya ha agregado "seleccionador de archivos" a la parte de declaraciones, que probablemente no sea lo que desea. La declaración del "selector de archivos" indica que si alguna otra aplicación invoca el selector de archivos, su aplicación aparecerá como una posible fuente de archivos.

También descubrí que agregar la capacidad de acceso a las bibliotecas de video o imagen en Manifest solo entra en efecto después de reiniciar Windows 10. Tal vez sea un problema con mi computadora, pero creo que vale la pena compartirlo.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top