0

I want to read a binary file using BinaryReader, but I keep getting an exception:

using (var stream = File.Open("file.bin", FileMode.Open, FileAccess.Read))
        {
            using (BinaryReader r = new BinaryReader(stream)) //EXCEPTION
            {

            }
        }

the "file.bin" has been set as a Content in the build action, but I keep getting this exception:

System.MethodAccessException was unhandled

Attempt to access the method failed: System.IO.File.Open(System.String, System.IO.FileMode, System.IO.FileAccess)

Ateik
  • 2,458
  • 4
  • 39
  • 59

1 Answers1

1

You don't use File.Open on Windows Phone 7 - you have to use isolated storage.

See the System.IO.IsolatedStorage namespace for more details.

For example:

using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
    using (var stream = store.OpenFile("file.bin", FileMode.Open))
    {
        using (var reader = new BinaryReader(stream))
        {

        }
    }
}

EDIT: As noted in comments, for content built into the XAP, you should use Application.GetResourceStream.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • but I need to read a file from the content of my xap file. can i access these files using IsolatedStroage? – Ateik Nov 25 '11 at 08:07
  • @user836252: Ah, you should have said. No, those won't be in isolated storage. I believe you need [`Application.GetResourceStream`](http://msdn.microsoft.com/en-us/library/ms596994(v=VS.95).aspx). See [this similar question](http://stackoverflow.com/questions/5045456/how-to-read-text-from-a-text-file-in-the-xap). – Jon Skeet Nov 25 '11 at 08:14
  • I've said it has been set as a content in the build action lol but thanks, it works using GetResourceStrea – Ateik Nov 25 '11 at 08:34