Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easy way to write data to local json file?

I'm using ASP.NET 5 (vNext) for a project right now but I've been having some issues with writing data to a local file. I've simply got som JSON data I want to put in an existing file in the public wwwroot folder. The JSON serialization etc. is no problem I just need some advice about available methods of writing to local files from an ASP.NET 5 MVC6 controller.

I'm using beta 7 right now and I've had no luck using streamwriter or File. All examples/suggestions will be much appreciated.

like image 574
jimutt Avatar asked Sep 14 '25 15:09

jimutt


2 Answers

Use http://www.newtonsoft.com/json.

public T Read()
{
     return JsonConvert.DeserializeObject<T>(File.ReadAllText(_filePath));
}
public void Write(T model)
{
     File.WriteAllText(_filePath, JsonConvert.SerializeObject(model));
}

I used it in my ASP.NET 5 project and it was okay

like image 160
Kostya Vyrodov Avatar answered Sep 17 '25 04:09

Kostya Vyrodov


You use the abstract TextWriter class in conjunction with the StreamWriter class e.g.

TextWriter writer;
using (writer = new StreamWriter(@"C:\SampleLog.json", append: false))
{
    writer.WriteLine(yourJsonString);
}
like image 33
Bon Macalindong Avatar answered Sep 17 '25 03:09

Bon Macalindong