how to store persistent data in C# without a database using json edit button Edit

Murugan Andezuthu Dharmaratnam | calendar 31 October 2020 | 4821

In this article, we will look at how to persist data in a C# application without using a database. The best way to persist data in an application without using a database would be to store it in a file. For simple data types, you can simply store the data in a text file. In my application, I want to save setup data, and for this, I will be storing the data in a file. The best format to store would be JSON as JSON data can easily be converted to objects and objects can easily be converted to JSON in an asp .net MVC or .net core application.

Sample Code

I have a class name CssSettings and I want to persist the data of this class.

public class CssSettings
    public String BackGroundImageURL { get; set; }
    public String FooterImageUrl { get; set; }

In the application first I read the data from the file

CssSettings cssSettings = GetSettings();

Check the code below to read JSON data from file and convert it to a C# object of type CssSettings

public CssSettings GetSettings()
     String file = HttpContext.Current.Server.MapPath(@"\adminjson.txt");
     String jsondata = System.IO.File.ReadAllText(file);
     if (String.IsNullOrEmpty(jsondata))
         return new CssSettings();
     CssSettings cssSettings = Newtonsoft.Json.JsonConvert.DeserializeObject(jsondata);
     return cssSettings;

Here is the sample code to modify the data and then save it to a text file

public void CreateCSS()
    String file1 = HttpContext.Current.Server.MapPath(@"\css\style-template.css");
    String data = System.IO.File.ReadAllText(file1);
    data = data.Replace("BackGroundImageURL", txtBackgroundImageUrl.Text);
    data = data.Replace("FooterImageUrl", txtFooterImageUrl.Text);

    SaveSettings(new CssSettings()
        BackGroundImageURL = txtBackgroundImageUrl.Text,
        FooterImageUrl = txtFooterImageUrl.Text
    String file2 = HttpContext.Current.Server.MapPath(@"\css\style.css");
    System.IO.File.WriteAllText(file2, data);