次の方法で共有


Creating a File

Demonstrates how to use the StorageContainer class to create 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.

Note

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 creating a save game file. You can download a complete code sample for this topic, including full source code and any additional supporting files required by the sample.

Download StorageDemo_Sample.zip

Creating a File

To create a save game file in user storage

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

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

  3. Call FileExists to confirm that the file is not already present.

  4. Call CreateFile with the name of the file to create.

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

  5. Call Close to close the file after you populate it with data.

  6. Call StorageContainer to commit the changes to the device.

private static void DoCreate(StorageDevice device)
{
    // Open a storage container.
    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";

    // Create a new file.
    if (!container.FileExists(filename))
    {
       Stream file = container.CreateFile(filename);
       file.Close();
    }
    // Dispose the container, to commit the data.
    container.Dispose();
}

See Also

Concepts

What Is Storage?

Reference

StorageDevice
BeginShowSelector
StorageContainer
CreateFile