XML Serialization in Windows 8

。_饼干妹妹 提交于 2019-12-24 05:28:22

问题


How can I Serialize Object in windows 8 Metro App Development to xml file ? I don't know how to create stream , when I create streamWriter I get error on the file direction

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

Error: The best overload method match 'system.io.streamwriter..streamwriter(system.io.stream) has some invalid arguments

this is the main code :

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

回答1:


Here is an example that I use. The Serialize call (last line in your code) looks wrong.

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;
        }
    }
}



回答2:


Here is a snippet from code I posted on a related post.

Writing Serialized XML To File

To serialize to XML asynchronously using Windows Storage for Windows 8 / RT:

/// <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);
        }
    }
}

Reading Serialized XML From File

To read from serialized XML asynchronously using Windows Storage for Windows 8 / RT:

/// <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;
    }
}

Both code snippets require having "using Windows.Storage" at the top of your file.

For me these are helper functions, which is why they are marked as static, but they don't need to be static. Also, the IsDebugging function is there just for sugar.




回答3:


If you don't want to ask user where to save a file you can save object to a local app folder or remote folder. Check this class: https://github.com/emilpytka/Win8Extensions/blob/master/Win8Extensions/Utils/ApplicationDataSerializer.cs

Sample for using this class: https://github.com/emilpytka/Win8Extensions/blob/master/Win8Extensions.Test/Utils/ApplicationDataSerializerTest.cs



来源:https://stackoverflow.com/questions/12562268/xml-serialization-in-windows-8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!