Search code examples
windows-phone-7binaryfilesbinaryreader

Reading Binary file on Windows phone


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)


Solution

  • 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.