Skip to content

Instantly share code, notes, and snippets.

@chinhvo
Forked from samilkorkmaz/JSONWriteRead.cs
Created May 26, 2021 06:42
Show Gist options
  • Save chinhvo/a7fed23d08fa2c7cbd2838e2ee53fc82 to your computer and use it in GitHub Desktop.
Save chinhvo/a7fed23d08fa2c7cbd2838e2ee53fc82 to your computer and use it in GitHub Desktop.
C# JSON save to and load from file
[DataContract]
public class UserInputs
{
[DataMember]
internal string ServerName;
[DataMember]
internal string IpAddress;
[DataMember]
internal int Port;
}
void Save(string JsonFileName)
{
var userInputs = new UserInputs { ServerName = "Local", IpAddress = "127.0.0.1", Port = 13000};
var stream1 = new MemoryStream();
var ser = new DataContractJsonSerializer(typeof(UserInputs));
ser.WriteObject(stream1, userInputs);
using (var fileStream = File.Create(JsonFileName))
{
stream1.Seek(0, SeekOrigin.Begin);
stream1.CopyTo(fileStream);
}
}
void Load(string JsonFileName)
{
var fsSource = new FileStream(JsonFileName, FileMode.Open, FileAccess.Read) {Position = 0};
var ser = new DataContractJsonSerializer(typeof(UserInputs));
var userInputs = (UserInputs)ser.ReadObject(fsSource);
MessageBox.Show(userInputs.IpAddress);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment