Renaming a File

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

Renaming a File

To rename 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 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 call CreateFile with the name of the new copy to be created.

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

  6. Call DeleteFile to delete the original file.

  7. Dispose of the StorageContainer to commit the changes to the device.

private static void DoRename(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 oldfilename = "demobinary.sav";
    string newfilename = "renamebinary.sav";

    if (container.FileExists(oldfilename) && !container.FileExists(newfilename))
    {
       Stream oldfile = container.OpenFile(oldfilename, FileMode.Open);
       Stream newfile = container.CreateFile(newfilename);
       oldfile.CopyTo(newfile);

       oldfile.Close();
       newfile.Close();
       container.DeleteFile(oldfilename);
    }

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

See Also

Concepts

What Is Storage?

Reference

StorageDevice
BeginShowSelector
StorageContainer