Saving/Loading Json string to/from .dat

454 Views Asked by At

I am trying to learn how to save a json string in a .dat file, but I have trouble converting it back to the correct json string. My new string at the end starts with 2 special characters (rest of it is correct) and I am not sure why.

//Saving
string save = "a json string";
string path = @"E:\tempTest\MyTest.dat";

if (!File.Exists(path))
{
    FileStream myFile = File.Create(path);
    BinaryWriter binaryfile = new BinaryWriter(myFile);
    binaryfile.Write(save);
    binaryfile.Close();
    myFile.Close();
}
//Loading
string path = @"E:\tempTest\MyTest.dat";

StreamReader objInput = new StreamReader(path, System.Text.Encoding.Default);
string contents = objInput.ReadToEnd().Trim();
string [] split = System.Text.RegularExpressions.Regex.Split(contents, "\\s+", RegexOptions.None);  
StringBuilder sb = new StringBuilder(); 
foreach (string s in split)
{
    sb.AppendLine(s);
}
string save = sb.ToString();    //string starts with 2 wrong special characters

I can obviously fix it with a simple save = save.Substring(2), but I would like to understand what the error was in my code (I guess the "\\s+" part of Regex is wrong).
Also, I am not exactly sure if this is still a good way of converting json to a data file and back. This example of how to do it, is from a 10 year old post I found online.

1

There are 1 best solutions below

0
On

As posted in the comments, I should have used BinaryReader to read the file. This solved the problem.

//Loading
string path = @"E:\tempTest\MyTest.dat";

var stream = File.Open(path, FileMode.Open);
var reader = new BinaryReader(stream, Encoding.UTF8, false);
string save = reader.ReadString();
stream.Close();
reader.Close();