Read and Write data from and to NotePad
Is this possible by C#? Yes, this is possible by
C#. Newtonsoft.Json.dll is
needed for this.
Well a ViewModel is need to be declared and
data will be read or written from or to notepad as a type of this ViewModel.
Writing an Object data into a notepad
public static void
WrieDataToNotePad(string filePath, Object
obj)
{
StreamWriter
writer = new StreamWriter(filePath);
string
jsonData = JsonConvert.SerializeObject(obj);
writer.Write(jsonData);
writer.Close();
}
Example:-
NotePadInteractor.WrieDataToNotePad(AppDomain.CurrentDomain.BaseDirectory
+ "AppData.txt", new NotePadData
{ RunApp=true,ModifiedMonth=DateTime.Today.Month});
Here NotePadData is a ViewModel.
If "AppData.txt"
is not available in the above
location(filePath), it’ll create a file with this name in that location. Data
will be stored in JSON format in the .txt file and can be used later in an
application as required.
Note:- JsonConvert.SerializeObject(obj) is a part of Newtonsoft.Json.dll
Reading an Object data from a notepad
public static NotePadData
ReadNotePadData(string filePath)
{
try
{
StreamReader
reader = new StreamReader(filePath);
string
jsonData = reader.ReadToEnd();
reader.Close();
return JsonConvert.DeserializeObject<NotePadData>(jsonData);
}
catch(Exception
ex)
{
return null;
throw
ex;
}
}
If location provided in the
filePath doesnot contain a file, with the given name then file not found
exception will be encountered. So in order to handle this exception, codes need
to be written in the catch block.
Type of ViewModel
need to be given in this function JsonConvert.DeserializeObject<ViewModelName>(jsonData);
Obviously, this function is
a part of Newtonsoft.Json.dll
No comments:
Post a Comment