Search code examples
c#file-iowindows-phone

Cannot access LocalFolder files on Windows phone app (UnauthorizedAccessException)


I am trying to get an application to write (then read) a simple text file in Windows Phone 8. My app has three controls: a create file button, a display file button, and a textbox where the contents are supposed to display.

I have the following events set up in my code:

private async void btnCreateFile_Click(object sender, RoutedEventArgs e)
    {
        await ApplicationData.Current.LocalFolder.CreateFileAsync("myFile.txt");
        StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync("myFile.txt");

        StreamWriter writer =  new StreamWriter(await file.OpenStreamForWriteAsync());

        writer.WriteLine("Hello World");
        writer.WriteLine("Goodbye world");
    }

    private async void btnShowFile_Click(object sender, RoutedEventArgs e)
    {
        StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync("myFile.txt");

        StreamReader reader = new StreamReader(await file.OpenStreamForReadAsync());

        string text = reader.ReadToEnd();
        text1.Text = text;

    }
}

The application is throwing UnauthorizedAccessException when the StreamReader is being created. Can anyone shed any light on why?


Solution

  • I guess you're not disposing the StreamWriter. See the example on MSDN.

     using( var writer =  new StreamWriter(await file.OpenStreamForWriteAsync()))
     {
            writer.WriteLine("Hello World");
            writer.WriteLine("Goodbye world");
      }
    

    That's why your can't read the file, because it's already taken by SreamWriter.