1

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?

tutiplain
  • 1,427
  • 4
  • 19
  • 37

2 Answers2

1

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.

Anton Sizikov
  • 9,105
  • 1
  • 28
  • 39
  • No wonder I couldn't find the Close() method anywhere! I had seen the MSDN example, but I didn't know that the using statement was absolutely necessary, I thought it was there as a memory optimization technique. – tutiplain Jun 15 '15 at 09:38
  • It's a Dispose for the Stream. – Anton Sizikov Jun 15 '15 at 09:43
  • and in fact there is a Close method as well https://msdn.microsoft.com/en-us/library/system.io.streamwriter.close(v=vs.110).aspx – Anton Sizikov Jun 15 '15 at 09:44
  • But for some reason, this method did not appear in my Intelisense. Could it not be available on Windows Phone? – tutiplain Jun 15 '15 at 09:50
  • 1
    sure it can. I don't have my WP dev environment now, but it's possible for sure. WP framework api is a subset of "big .net". – Anton Sizikov Jun 15 '15 at 09:52
0

Always use 'using' statement when using an object that inherits from IDisposable.

You are trying to write to an already opened file and this gives you UnauthoritedException.

Try using your code block inside of using.Check out this question to find more about StreamWriter :

how to use StreamWriter class properly?

Community
  • 1
  • 1
Burak Kaan Köse
  • 821
  • 1
  • 7
  • 18