Export (0) Print
Expand All
1 out of 3 rated this helpful - Rate this topic

Opening a File for Reading/Writing

Demonstrates how to use the StorageContainer class to open a save game file in the user storage area on a device specified by the gamer. This example assumes you obtained a StorageDevice, if not, see Getting a StorageDevice Asynchronously.

Bb199095.note(en-us,XNAGameStudio.41).gifNote

The simplified example code demonstrates synchronous usage of BeginOpenContainer through the WaitOne method accessible through IAsyncResult.AsyncWaitHandle.

The preferred technique to use this function asynchronously is similar to the technique demonstrated in the Getting a StorageDevice Asynchronously topic.

Complete Sample

The code in the topic shows you the technique for opening a save game file for reading and writing. You can download a complete code sample for this topic, including full source code and any additional supporting files required by the sample.

Opening a File

To open a save game file in user storage

  1. Call the StorageDevice.BeginShowSelector method to get a device index indicating which device the user prefers.

  2. Call BeginOpenContainer to open a StorageContainer on the device that is assigned the name of your title.

  3. Call OpenFile with the name of the file to open. You also may specify any FileMode, FileAccess, and FileShare attributes you require by using the appropriate overload of the method.

    OpenFile returns a Stream object that you can use to add data to the file.

  4. Call Close to close the file after it is read.

  5. Dispose the StorageContainer after closing the file.

private static void DoOpen(StorageDevice device)
{
    IAsyncResult result =
        device.BeginOpenContainer("StorageDemo", null, null);

    // Wait for the WaitHandle to become signaled.
    result.AsyncWaitHandle.WaitOne();

    StorageContainer container = device.EndOpenContainer(result);

    // Close the wait handle.
    result.AsyncWaitHandle.Close();

    // Add the container path to our file name.
    string filename = "demobinary.sav";

    Stream file = container.OpenFile(filename, FileMode.Open);
    file.Close();

    // Dispose the container.
    container.Dispose();
}
Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.