Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

filestream

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

like image 281
Federinik Avatar asked Apr 23 '13 15:04

Federinik


2 Answers

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);
}
like image 100
Dustin Kingen Avatar answered Oct 11 '22 01:10

Dustin Kingen


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
like image 45
Tim S. Avatar answered Oct 11 '22 01:10

Tim S.