【发布时间】:2016-03-03 11:53:02
【问题描述】:
我在 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();
}
【问题讨论】:
-
你得到的确切错误?
-
第一种方法 (SaveTextAsync) 没有给出任何错误,但第二种方法 (LoadTextAsync) 给出了任何错误。
Error 5 'LoadTextAsync(string)': not all code paths return a value -
看起来您有一个双端口应用程序,您可以在其中读取/写入流并写入/读取文件。通常代码的异步部分会在流上而不是文件上。
-
@jdweng 你能解释一下怎么做吗?
-
检查这个例子。 stephenhaunts.com/2014/10/10/…
标签: c# xml asynchronous xamarin.forms