提问人:MP9 提问时间:4/30/2022 最后编辑:MP9 更新时间:5/2/2022 访问量:565
NullReferenceException - File.WriteAllText Xamarin/Android
NullReferenceException - File.WriteAllText Xamarin/Android
问:
我是 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)}
有人知道这里发生了什么吗?当然,我可以提供这个类的全部代码,但我认为这并没有真正解决这个问题。
答:
尝试更改此内容:
if (File.Exists("RecentHosts.json")) File.Create("RecentHosts.json");
对此:
if (!File.Exists("RecentHosts.json")) File.Create("RecentHosts.json");
当文件已经存在时,您正在创建文件,而您想要的是创建它,如果它不存在。
评论
出现错误是因为您写入的路径无效,我们必须设置一个完整的文件夹路径。
请尝试以下代码
//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);
评论
text