NullReferenceException - File.WriteAllText Xamarin/Android

NullReferenceException - File.WriteAllText Xamarin/Android

提问人:MP9 提问时间:4/30/2022 最后编辑:MP9 更新时间:5/2/2022 访问量:565

问:

我是 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)}

有人知道这里发生了什么吗?当然,我可以提供这个类的全部代码,但我认为这并没有真正解决这个问题。

c# 人造人 Xamarin NullReferenceException

评论

0赞 Klaus Gütter 4/30/2022
你能在调试器中看看吗?text
0赞 Klaus Gütter 4/30/2022
这回答了你的问题吗?什么是 NullReferenceException,如何修复它?

答:

0赞 ekke 4/30/2022 #1

尝试更改此内容:

if (File.Exists("RecentHosts.json")) File.Create("RecentHosts.json");

对此:

if (!File.Exists("RecentHosts.json")) File.Create("RecentHosts.json");

当文件已经存在时,您正在创建文件,而您想要的是创建它,如果它不存在。

评论

0赞 Klaus Gütter 4/30/2022
只在下面覆盖 2 行?
0赞 MP9 5/2/2022
是的,那是我的错......但这并不能改变任何事情
0赞 ColeX 5/2/2022 #2

出现错误是因为您写入的路径无效,我们必须设置一个完整的文件夹路径。

请尝试以下代码

//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);

评论

0赞 ColeX 5/11/2022
它是否有效?