Introducing the WinPRT Windows Storage API

,

The Windows Storage API resembles the Isolated Storage API with one key difference: the API is predominately asynchronous, with the majority of its methods being awaitable.

The Windows Storage API is located in the Windows.Storage namespace.

The StorageFolder and StorageFile classes underpin the Windows Storage API and represent folders and files within the local folder.

To retrieve the StorageFolder representing the local folder of your app, use the ApplicationData.Current.LocalFolder property. Observe the following method, which writes some text to a new file in the local folder:

async void SaveSampleFile()
{
    string assemblyName = Assembly.GetExecutingAssembly().FullName;
    assemblyName = assemblyName.Substring(
        0, assemblyName.IndexOf(",", StringComparison.Ordinal));

    string fileContent = string.Format(
        "This text was saved to a file at {0} from the assembly: {1}.",
        DateTime.Now, assemblyName);

    IStorageFolder folder = ApplicationData.Current.LocalFolder;
    IStorageFile file = await folder.CreateFileAsync(
                                fileName, CreationCollisionOption.ReplaceExisting);

    using (Stream stream = await file.OpenStreamForWriteAsync())
    {
        byte[] content = Encoding.UTF8.GetBytes(fileContent);
        await stream.WriteAsync(content, 0, content.Length);
    }
}

Creating a file is achieved using the IStorageFolder object’s CreateFileAsync method. This method is awaitable, which means that you can perform the IO operation without blocking the UI thread.

The StorageFolder class implements IStorageFolder, and it is a good practice to use the interface API rather than the concrete class wherever possible.

As with the .NET Isolate Storage API, the Windows Storage API is stream based. You can see in the previous excerpt that writing bytes to the file is achieved using the awaitable Stream.WriteAsync method.

You look at performing other IO operations using the Windows Storage API in Chapter 30, “Auto-Launching with File and Protocol Associations.”

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.198.120