-
-
Save chinhvo/a7fed23d08fa2c7cbd2838e2ee53fc82 to your computer and use it in GitHub Desktop.
C# JSON save to and load from file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[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