2

如何将 Windows 8 Metro App Development 中的对象序列化为 xml 文件?我不知道如何创建流,当我创建 streamWriter 时,文件方向出现错误

StreamWriter nsw = new StreamWriter(@"C:\sample.xml");

错误:最佳重载方法匹配 'system.io.streamwriter..streamwriter(system.io.stream) 有一些无效参数

这是主要代码:

 StorageFolder storageFolder = KnownFolders.DocumentsLibrary;
 StorageFile sampleFile = await storageFolder.CreateFileAsync("sample.xml");
 XmlSerializer serializer = new XmlSerializer(ob.GetType());
 serializer.Serialize(Stream stream,ob);
4

3 回答 3

2

这是我使用的一个例子。Serialize 调用(代码中的最后一行)看起来不对。

private async void SaveButton_Click(object sender, RoutedEventArgs e)
{
    FileSavePicker fileSavePicker = new FileSavePicker();
    fileSavePicker.DefaultFileExtension = ".bla";
    fileSavePicker.FileTypeChoices.Add("Bla Files", new List<string> { ".bla" });
    fileSavePicker.SuggestedFileName = "New Bla File";
    fileSavePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
    var file = await fileSavePicker.PickSaveFileAsync();
    if (file != null)
    {
        using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
        {
            XmlSerializer serializer = new XmlSerializer(typeof(TypeToBeSerialized));
            serializer.Serialize(stream.AsStreamForWrite(), objectToBeSerialized);
            await stream.FlushAsync();
            stream.Size = stream.Position;
        }
    }
}
于 2012-09-24T09:37:31.713 回答
1

这是我在相关帖子上发布的代码片段。

将序列化的 XML 写入文件

使用适用于 Windows 8 / RT 的 Windows 存储异步序列化为 XML:

/// <summary>
/// Saves the given class instance as XML asynchronously.
/// </summary>
/// <param name="fileName">Name of the xml file to save the data to.</param>
/// <param name="classInstanceToSave">The class instance to save.</param>
public static async void SaveToXmlAsync(string fileName, T classInstanceToSave)
{
    using (var stream = await ApplicationData.Current.LocalFolder.OpenStreamForWriteAsync(fileName, CreationCollisionOption.ReplaceExisting))
    {
        XmlSerializer serializer = new XmlSerializer(typeof(T));
        using (XmlWriter xmlWriter = XmlWriter.Create(stream, new XmlWriterSettings() { Indent = true }))
        {
            serializer.Serialize(xmlWriter, classInstanceToSave);
        }
    }
}

从文件中读取序列化 XML

使用适用于 Windows 8 / RT 的 Windows 存储异步读取序列化 XML:

/// <summary>
/// Loads a class instance from an XML file asynchronously.
/// </summary>
/// <param name="fileName">Name of the file to load the data from.</param>
public static async System.Threading.Tasks.Task<T> LoadFromXmlAsync(string fileName)
{
    try
    {
        var files = ApplicationData.Current.LocalFolder.GetFilesAsync(Windows.Storage.Search.CommonFileQuery.OrderByName).GetResults();
        var file = files.FirstOrDefault(f => f.Name == fileName);

        // If the file exists, try and load it it's data.
        if (file != null)
        {
            using (var stream = await ApplicationData.Current.LocalFolder.OpenStreamForReadAsync(fileName))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(T));
                T data = (T)serializer.Deserialize(stream);
                return data;
            }
        }
    }
    // Eat any exceptions unless debugging so that users don't see any errors.
    catch
    {
        if (IsDebugging)
            throw;
    }

    // We couldn't load the data, so just return a default instance of the class.
    return default(T);
}

/// <summary>
/// Gets if we are debugging the application or not.
/// </summary>
private static bool IsDebugging
{
    get
    {
#if (DEBUG)
        // Extra layer of protection in case we accidentally release a version compiled in Debug mode.
        if (System.Diagnostics.Debugger.IsAttached)
            return true;
#endif
        return false;
    }
}

两个代码片段都需要在文件顶部添加“使用 Windows.Storage”。

对我来说,这些是辅助函数,这就是为什么它们被标记为静态的,但它们不需要是静态的。此外,IsDebugging 函数仅用于糖。

于 2013-06-11T23:50:12.787 回答
0

如果您不想询问用户将文件保存在哪里,您可以将对象保存到本地应用程序文件夹或远程文件夹。检查这个类:https ://github.com/emilpytka/Win8Extensions/blob/master/Win8Extensions/Utils/ApplicationDataSerializer.cs

使用此类的示例: https ://github.com/emilpytka/Win8Extensions/blob/master/Win8Extensions.Test/Utils/ApplicationDataSerializerTest.cs

于 2014-03-06T11:46:20.853 回答