我对Xamarin很陌生,所以我搜索了一种在Android/iOS上轻松保存文件的方法。发现File.ReadAllText/File.WriteAllText应该能工作..。当我调用File.WriteAllText()时,会抛出一个NullReferenceException。
这是密码。原来只是一句台词。但我把它分开做了些测试。
public static void SAVE()
{
if (!File.Exists("RecentHosts.json")) File.Create("RecentHosts.json");
string text = JsonConvert.SerializeObject(new JsonHosts() { hosts = RecentHosts.Values.ToList() });
File.WriteAllText("RecentHosts.json", text);
}这就是我从例外中得到的全部:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
{System.NullReferenceException: Object reference not set to an instance of an object. at Android.Runtime.JNINativeWrapper._unhandled_exception (System.Exception e) [0x0000e] in /Users/runner/work/1/s/xamarin-android/src/Mono.Android/Android.Runtime/JNINativeWrapper.g.cs:12 at Android.Runtime.JNINativeWrapper.Wrap_JniMarshal_PPL_V (_JniMarshal_PPL_V callback, System.IntPtr jnienv, System.IntPtr klazz, System.IntPtr p0) [0x0001d] in /Users/runner/work/1/s/xamarin-android/src/Mono.Android/Android.Runtime/JNINativeWrapper.g.cs:111 at (wrapper native-to-managed) Android.Runtime.JNINativeWrapper.Wrap_JniMarshal_PPL_V(intptr,intptr,intptr)}
有人知道这里发生了什么吗?当然,我可以提供这个类的全部代码,但我认为这并不能真正解决这个问题。
发布于 2022-04-30 10:47:11
试着改变这个:
if (File.Exists("RecentHosts.json")) File.Create("RecentHosts.json");对此:
if (!File.Exists("RecentHosts.json")) File.Create("RecentHosts.json");当文件已经存在时,您正在创建它,如果它不存在,则创建它。
发布于 2022-05-02 05:21:47
错误发生是因为您写入的路径无效,我们必须设置一个完整的文件夹路径。
尝试以下代码
//file path
var filePath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "RecentHosts.txt");
if (!File.Exists(filePath))
{
File.Create(filePath);
}
string text = JsonConvert.SerializeObject(new JsonHosts() { hosts = RecentHosts.Values.ToList() });
//write in file
File.WriteAllText(filePath, text);https://stackoverflow.com/questions/72067415
复制相似问题