Export (0) Print
Expand All

Copying a File

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

Bb199090.note(en-us,XNAGameStudio.40).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 copying 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.

Copying a File

To copy 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 original file exists and that the destination file does not exist.

  4. Call OpenFile with the name of the file to copy, and then call CreateFile with the name of the new file to be created.

  5. Call Stream.CopyTo to copy the file to the newly created file.

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

private static void DoCopy(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";
    string copyfilename = "copybinary.sav";

    if (container.FileExists(filename) && !container.FileExists(copyfilename))
    {
        Stream file = container.OpenFile(filename, FileMode.Open);
       Stream copyfile = container.CreateFile(copyfilename);
       file.CopyTo(copyfile);

       file.Close();
       copyfile.Close();
    }

    // Dispose the container, to commit the change.
    container.Dispose();
}

Community Additions

ADD
Show:
© 2014 Microsoft