Home > Net >  NullReferenceException - File.WriteAllText Xamarin/Android
NullReferenceException - File.WriteAllText Xamarin/Android

Time:05-02

I'm new to Xamarin, so I searched for a way to easily save file on Android/iOS. Found that File.ReadAllText/File.WriteAllText should work... When I call File.WriteAllText() a NullReferenceException is thrown.

Here is the code. Originally it was just one line. But I split it up to do some testing.

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

That's all I get from the Exception:

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

Has anyone any idea what's happening here? Of course, I can provide the whole code from this class, but I don't think that's doing really anything to solve this.

CodePudding user response:

Try changing this:

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

To this:

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

You're creating the file when it already exists, when what you want to is create it if it doesn't.

CodePudding user response:

The error occurs because the path you write in is invalid, we have to set a complete folder path .

Try the following code

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