---
# System prepended metadata

title: '[C# Winform] - Studying .ini, .xml, and .json files for reading and writing'

---

Github: [https://github.com/CarterWu-M/CS-WinForm_data-file-read-write]

This article introduces how to read and write three types of data formats: .ini, .xml, and .json. By working with these formats, you can get a sense of the complexity involved in handling each format.
![image](https://hackmd.io/_uploads/rkjFFMzG1g.png)
![image](https://hackmd.io/_uploads/ryxzv4fzyg.png)



---
### .ini file
---
![image](https://hackmd.io/_uploads/SJP2Kzzfye.png)
![image](https://hackmd.io/_uploads/Hy4ksMMMkl.png)
![image](https://hackmd.io/_uploads/H1NZEmGzJx.png)
```c#=
internal class IniFile
{
    public string Path { get; set; }

    [DllImport("kernel32", CharSet = CharSet.Unicode)]
    private static extern long WritePrivateProfileString(string section, string key, string value, string filePath);

    [DllImport("kernel32", CharSet = CharSet.Unicode)]
    private static extern int GetPrivateProfileString(string section, string key, string defaultValue, StringBuilder retVal, int size, string filePath);

    public IniFile(string path)
    {
        Path = path;
    }

    public void Write(string section, string key, string value)
    {
        WritePrivateProfileString(section, key, value, Path);
    }

    public string Read(string section, string key)
    {
        var retVal = new StringBuilder(255);
        int ret = GetPrivateProfileString(section, key, "", retVal, 255, Path);
        if (0 == ret)
        {
            // Check for last error if needed
            int errorCode = Marshal.GetLastWin32Error();
            Console.WriteLine($"Error reading INI file: {errorCode} (0x{errorCode:X})");
        }
        return retVal.ToString();
    }
}
```

![image](https://hackmd.io/_uploads/SkzJN7Gf1e.png)
```c#=
public partial class Form1 : Form
{
    string szIniFilePath = "Data/data.ini";
    private Dictionary<TextBox, (string, string)> _arrIniT;

    public Form1()
    {
        InitializeComponent();

        initTable();
        readIniFile();
    }
        
    private void initTable()
    {
        this._arrIniT = new Dictionary<TextBox, (string, string)>
        {
            {txtR1Min, ("TestPoint1", "ImpedanceMin")},
            {txtR1Max, ("TestPoint1", "ImpedanceMax")},
            {txtV1Min, ("TestPoint1", "VoltageMin")},
            {txtV1Max, ("TestPoint1", "VoltageMax")},
            {txtI1Min, ("TestPoint1", "CurrentMin")},
            {txtI1Max, ("TestPoint1", "CurrentMax")},
            {txtP1Min, ("TestPoint1", "PowerMin")},
            {txtP1Max, ("TestPoint1", "PowerMax")},
            {txtR2Min, ("TestPoint2", "ImpedanceMin")},
            {txtR2Max, ("TestPoint2", "ImpedanceMax")},
            {txtV2Min, ("TestPoint2", "VoltageMin")},
            {txtV2Max, ("TestPoint2", "VoltageMax")},
        };
    }
        
    private void readIniFile()
    {
        var iniFile = new IniFile(szIniFilePath);

        foreach (var item in this._arrIniT)
        {
            item.Key.Text = iniFile.Read(item.Value.Item1, item.Value.Item2);
        }
    }

    private void writeIniFile()
    {
        var iniFile = new IniFile(szIniFilePath);

        foreach (var item in this._arrIniT)
        {
            iniFile.Write(item.Value.Item1, item.Value.Item2, item.Key.Text);
        }
    }
    
    private void btnRead_Click(object sender, EventArgs e)
    {
        readIniFile();
    }
    private void btnWrite_Click(object sender, EventArgs e)
    {
        writeIniFile();
    }
    
    private void btnClear_Click(object sender, EventArgs e)
    {
        foreach (Control control in this.Controls)
        {
            if (control is TextBox textBox)
            {
                textBox.Clear();
            }
        }
    }
    
}
```

---
### .xml file
---
![image](https://hackmd.io/_uploads/rk_xcGzzJl.png)
![image](https://hackmd.io/_uploads/HkKfsfMz1e.png)
![image](https://hackmd.io/_uploads/SJOCQQfM1l.png)
```C#=
public partial class Form1 : Form
{
    string szXmlFilePath = "Data/data.xml";
    private XmlDocument _doc = new XmlDocument();
    private Dictionary<TextBox, string> _arrXmlT;

    public Form1()
    {
        InitializeComponent();

        initTable();
        readXmlFile();
    }
        
    private void initTable()
    {
        this._arrXmlT = new Dictionary<TextBox, string> 
        {
            {txtR1Min, "/root/TestPoint1/Impedance/Min"},
            {txtR1Max, "/root/TestPoint1/Impedance/Max"},
            {txtV1Min, "/root/TestPoint1/Voltage/Min"},
            {txtV1Max, "/root/TestPoint1/Voltage/Max"},
            {txtI1Min, "/root/TestPoint1/Current/Min"},
            {txtI1Max, "/root/TestPoint1/Current/Max"},
            {txtP1Min, "/root/TestPoint1/Power/Min"},
            {txtP1Max, "/root/TestPoint1/Power/Max"},
            {txtR2Min, "/root/TestPoint2/Impedance/Min"},
            {txtR2Max, "/root/TestPoint2/Impedance/Max"},
            {txtV2Min, "/root/TestPoint2/Voltage/Min"},
            {txtV2Max, "/root/TestPoint2/Voltage/Max"},
        };
    }
        
    private void readXmlFile()
    {
        this._doc.Load(szXmlFilePath);

        foreach (var entry in this._arrXmlT)
        {
            XmlNode node = this._doc.SelectSingleNode(entry.Value);
            if (null != node) 
            { 
                entry.Key.Text = node.InnerText; 
            }
        }
    }

    private void writeXmlFile()
    {
        this._doc.Load(szXmlFilePath);

        foreach (var entry in this._arrXmlT)
        {
            XmlNode node = this._doc.SelectSingleNode(entry.Value);
            if (null != node)
            {
                node.InnerText = entry.Key.Text;
            }
        }
        this._doc.Save(szXmlFilePath);
    }
    
    private void btnRead_Click(object sender, EventArgs e)
    {
        readXmlFile();
    }
    private void btnWrite_Click(object sender, EventArgs e)
    {
        writeXmlFile();
    }
    
    private void btnClear_Click(object sender, EventArgs e)
    {
        foreach (Control control in this.Controls)
        {
            if (control is TextBox textBox)
            {
                textBox.Clear();
            }
        }
    }
    
}
```

---
### .json file
---
![image](https://hackmd.io/_uploads/BkYAKGzzyx.png)
![image](https://hackmd.io/_uploads/HJ6VifzzJg.png)
![image](https://hackmd.io/_uploads/SJdkQ7Gfyl.png)
```C#=
internal class jsonFile
{
    public class Impedance
    {
        public double Min { get; set; }
        public double Max { get; set; }
    }
    public class Voltage
    {
        public double Min { get; set; }
        public double Max { get; set; }
    }
    public class Current
    {
        public double Min { get; set; }
        public double Max { get; set; }
    }
    public class Power
    {
        public double Min { get; set; }
        public double Max { get; set; }
    }
    public class TestPoint1
    {
        public Impedance Impedance { get; set; }
        public Voltage Voltage { get; set; }
        public Current Current { get; set; }
        public Power Power { get; set; }
    }
    public class TestPoint2
    {
        public Impedance Impedance { get; set; }
        public Voltage Voltage { get; set; }
    }

    public class Root
    {
        public TestPoint1 TestPoint1 { get; set; }
        public TestPoint2 TestPoint2 { get; set; }
    }
}
```
![image](https://hackmd.io/_uploads/Hy86mQzGJe.png)

```C#=
public partial class Form1 : Form
{
    string szJsonFilePath = "Data/data.json";
    private jsonFile.Root _data;
    private Dictionary<TextBox, (Func<double> getter, Action<double> setter)> _arrJsonT;

    public Form1()
    {
        InitializeComponent();

        initTable();
        readJsonFile();
    }
        
    private void initTable()
    {
        this._arrJsonT = new Dictionary<TextBox, (Func<double> getter, Action<double> setter)>
        {
            {txtR1Min, (() => _data.TestPoint1.Impedance.Min, value => _data.TestPoint1.Impedance.Min = value) },
            {txtR1Max, (() => _data.TestPoint1.Impedance.Max, value => _data.TestPoint1.Impedance.Max = value) },
            {txtV1Min, (() => _data.TestPoint1.Voltage.Min, value => _data.TestPoint1.Voltage.Min = value) },
            {txtV1Max, (() => _data.TestPoint1.Voltage.Max, value => _data.TestPoint1.Voltage.Max = value) },
            {txtI1Min, (() => _data.TestPoint1.Current.Min, value => _data.TestPoint1.Current.Min = value) },
            {txtI1Max, (() => _data.TestPoint1.Current.Max, value => _data.TestPoint1.Current.Max = value) },
            {txtP1Min, (() => _data.TestPoint1.Power.Min, value => _data.TestPoint1.Power.Min = value) },
            {txtP1Max, (() => _data.TestPoint1.Power.Max, value => _data.TestPoint1.Power.Max = value) },
            {txtR2Min, (() => _data.TestPoint2.Impedance.Min, value => _data.TestPoint2.Impedance.Min = value) },
            {txtR2Max, (() => _data.TestPoint2.Impedance.Max, value => _data.TestPoint2.Impedance.Max = value) },
            {txtV2Min, (() => _data.TestPoint2.Voltage.Min, value => _data.TestPoint2.Voltage.Min = value) },
            {txtV2Max, (() => _data.TestPoint2.Voltage.Max, value => _data.TestPoint2.Voltage.Max = value) },
        };
    }
        
    private void textChanged(object sender, EventArgs e)
    {
        if (sender is TextBox textBox && _arrJsonT.TryGetValue(textBox, out var binding))
        {
            if (double.TryParse(textBox.Text, out double newValue))
            {
                // Update the corresponding JSON property
                binding.setter(newValue);
            }
        }
    }
    
    private void readJsonFile()
    {
        string jsonString = File.ReadAllText(this.szJsonFilePath);
        this._data = JsonSerializer.Deserialize<jsonFile.Root>(jsonString);

        foreach (var textBox in this._arrJsonT.Keys)
        {
            textBox.Text = this._arrJsonT[textBox].getter().ToString();
            textBox.TextChanged += textChanged;
        }
    }

    private void writeJsonFile()
    {
        var option = new JsonSerializerOptions { WriteIndented = true };
        string szJsonStr = JsonSerializer.Serialize(this._data, option);
        File.WriteAllText(this.szJsonFilePath, szJsonStr);
    }
    
    private void btnRead_Click(object sender, EventArgs e)
    {
        readJsonFile();
    }
    private void btnWrite_Click(object sender, EventArgs e)
    {
        writeJsonFile();
    }
    
    private void btnClear_Click(object sender, EventArgs e)
    {
        foreach (Control control in this.Controls)
        {
            if (control is TextBox textBox)
            {
                textBox.Clear();
            }
        }
    }
    
}
```
---
### Youtube videio
---
{%youtube 84UsqbVp_5M %}