我使用Xamarin.forms制作跨平台应用程序,我需要在本地目录中写入以保存数据。通过我的研究,我发现它的行为方式不一样在iOS和Android中。我尝试了一些东西,但它不起作用:
public string ReadData()
{
string filePath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.Personal),
"Data.txt");
var data = System.IO.File.ReadAllText(filePath);
return data;
}
public void WriteData(string data)
{
string filepath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal),"Data.txt");
System.IO.File.WriteAllText(filePath, data);
}
我收到此错误:
`System.Environment' does not contain a definition for `GetFolderPath'
和:
The type or namespace `File' does not exist in the namespace `System.IO'.
提前感谢您的帮助。
答案 0 :(得分:1)
您可能想在Xamarin.Forms documentation
中检查此位您必须通过DependencyService使用特定于平台的实施(假设您使用PCL作为共享代码)。
从文档页面中获取:在您的共享PCL代码中,以<StackLayout orientation="horizontal">
<Switch checked="true"></Switch>
<Button isEnabled="true" text="This is a Button!"></Button>
</StackLayout>
的形式创建一个抽象,例如,如果您想要在文本文件中写入和加载,请创建一个抽象:
Interface
现在,对于Android和iOS,文档指定您可以创建相同的实现(这可能会直接从您的共享代码中暗示它。您应该尝试使用它。)
注意:您仍然需要为每个平台创建一个实现,这也允许您调整每个平台的实现。
public interface ISaveAndLoad {
void SaveText (string filename, string text);
string LoadText (string filename);
}