Federinik
Federinik

Reputation: 521

How do I get the name of a file generated with a stream in C#?

I'm building a Windows 8 metro app with XAML/C#. I'm saving an .xml file my data structure with a stream, like this:

XmlSerializer serializer = new XmlSerializer(typeof(MyObjectType));

using (var stream = await App.LocalStorage.OpenStreamForWriteAsync(MyObject.Title + ".xml", Windows.Storage.CreationCollisionOption.GenerateUniqueName))
    serializer.Serialize(stream, MyObject);

Where:

App.LocalStorage

Is obviously a StorageFolder objecty set to

Windows.Storage.ApplicationData.Current.LocalFolder

The GenerateUniqueName option is set in order to avoid collisions, because my objects can have the same title. Now, I need to get the file name my stream generated, how can I get it?

Thank you

Upvotes: 10

Views: 369

Answers (2)

Tim S.
Tim S.

Reputation: 56536

The OpenStreamForWriteAsync method does not seem to give you any easy way to access this information. You could switch to accessing it another way:

StorageFile file = await App.LocalStorage.CreateFileAsync(...);
using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
    // do stuff, file name is at file.Name

Upvotes: 2

Dustin Kingen
Dustin Kingen

Reputation: 21245

Try creating the file first.

var sourceFileName = MyObject.Title + ".xml";
StorageFile storageFile = await App.LocalStorage.CreateFileAsync(sourceFileName, Windows.Storage.CreationCollisionOption.GenerateUniqueName);

using (var stream = await storageFile.OpenAsync(FileAccessMode.ReadWrite))
{
    serializer.Serialize(stream, MyObject);
}

Upvotes: 10

Related Questions