我在Play商店中有一个用Java和Android Studio编写的应用程序,我希望将其替换为用C#和Xamarin编写的应用程序。
除一件事外,一切都进展顺利。我的Xamarin代码似乎无法读取旧的基于Java的应用程序具有的,存储用户设置和数据的文件。
我使用了相同的软件包名称,并且还使用了相同的证书对应用程序进行签名。我以为我也可以访问同一目录。
这是我使用活动上下文将文件保存在Android Studio中的方法:
byte[] data = {0, 1, 2, 3, 4};
try (FileOutputStream stream = context.get().openFileOutput("file.dat", Context.MODE_PRIVATE)) {
stream.write(data);
}
这就是我试图用C#读取文件的方式
using (Stream stream = CustomClass.MainActivity.OpenFileInput("file.dat"))
{
byte[] data = new byte[stream.Length];
stream.Read(data, 0, data.Length);
}
C#代码看不到该文件,并且在使用MainActivity.FileList()枚举所有文件时,它也未显示在该文件上。
任何帮助将不胜感激。
答案 0 :(得分:1)
string tag = "myapp";
var file = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "file.dat");
if (file == null || !File.Exists(file))
{
Log.Warn(tag, "file not exists");
}
else
{
using (var stream = File.OpenRead(file))
{
byte[] data = new byte[stream.Length];
stream.Read(data, 0, data.Length);
}
}
阅读官方文档以了解更多信息: File Storage and Access with Xamarin.Android
由于我们需要经常运行调试apk,因此还要确保使用相同的keystore
签名,因此可以通过手动配置调试密钥库来实现: