首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NullReferenceException - File.WriteAllText Xamarin/Android

NullReferenceException - File.WriteAllText Xamarin/Android
EN

Stack Overflow用户
提问于 2022-04-30 09:53:53
回答 2查看 398关注 0票数 0

我对Xamarin很陌生,所以我搜索了一种在Android/iOS上轻松保存文件的方法。发现File.ReadAllText/File.WriteAllText应该能工作..。当我调用File.WriteAllText()时,会抛出一个NullReferenceException。

这是密码。原来只是一句台词。但我把它分开做了些测试。

代码语言:javascript
复制
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)}

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

EN

回答 2

Stack Overflow用户

发布于 2022-04-30 10:47:11

试着改变这个:

代码语言:javascript
复制
if (File.Exists("RecentHosts.json")) File.Create("RecentHosts.json");

对此:

代码语言:javascript
复制
if (!File.Exists("RecentHosts.json")) File.Create("RecentHosts.json");

当文件已经存在时,您正在创建它,如果它不存在,则创建它。

票数 0
EN

Stack Overflow用户

发布于 2022-05-02 05:21:47

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

尝试以下代码

代码语言:javascript
复制
//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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72067415

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档