用于读写XML文件的异步方法

时间:2016-03-03 11:53:03

标签: c# xml asynchronous xamarin.forms

我在android / ios和windows phone中使用DependencyService来编写和读取我的Xamarin.forms项目中的XML文件。我指的是working with files

我能够实现示例中给出的功能,但我真正想要的是读取和写入XML文件。

我按照通常的c#过程来读取和写入xml文件,但由于方法是异步的,因此会出错。

我从未使用异步等待方法,所以不确定如何去做。

以下是我的尝试:

public async Task SaveTextAsync(string filename, string text)
{
    ApplicationData data = new ApplicationData();
    ApplicationVersion version = new ApplicationVersion();
    version.SoftwareVersion = "test";
    data.ApplicationVersion = version;

    XmlSerializer writer =
        new XmlSerializer(typeof(ApplicationData));
    System.IO.FileStream file = System.IO.File.Create(path);

    writer.Serialize(file, data);
    file.Close();
}

public async Task<string> LoadTextAsync(string filename)
{
    var path = CreatePathToFile(filename);
    ApplicationData cars = null;
    XmlSerializer serializer = new XmlSerializer(typeof(ApplicationData));
    StreamReader reader = new StreamReader(path);
    cars = (ApplicationData)serializer.Deserialize(reader);
    reader.Close();
}
string CreatePathToFile(string filename)
{
    var docsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
    return Path.Combine(docsPath, filename);
}

修改

工作读取和写入txt文件代码在这里:

public async Task SaveTextAsync (string filename, string text)
{
    var path = CreatePathToFile (filename);
    using (StreamWriter sw = File.CreateText (path))
        await sw.WriteAsync(text);
}

public async Task<string> LoadTextAsync (string filename)
{
    var path = CreatePathToFile (filename);
    using (StreamReader sr = File.OpenText(path))
        return await sr.ReadToEndAsync();
}

1 个答案:

答案 0 :(得分:-1)

我设法让它发挥作用。这是我的代码:

public async Task SaveTextAsync(string filename)
{
    var path = CreatePathToFile(filename);
    ApplicationData data = new ApplicationData();
    ApplicationVersion version = new ApplicationVersion();
    version.SoftwareVersion = "test version";
    data.ApplicationVersion = version;
    XmlSerializer writer =
        new XmlSerializer(typeof(ApplicationData));
    System.IO.FileStream file = System.IO.File.Create(path);
    writer.Serialize(file, data);
    file.Close();

}

public async Task<ApplicationData> LoadTextAsync(string filename)
{
    var path = CreatePathToFile(filename);

    ApplicationData records = null;
    await Task.Run(() =>
    {
        // Create an instance of the XmlSerializer specifying type and namespace.
        XmlSerializer serializer = new XmlSerializer(typeof(ApplicationData));

        // A FileStream is needed to read the XML document.
        FileStream fs = new FileStream(path, FileMode.Open);
        XmlReader reader = XmlReader.Create(fs);

        // Use the Deserialize method to restore the object's state.
        records = (ApplicationData)serializer.Deserialize(reader);
        fs.Close();
    });
    return records;
}