在C#中,如何将ini文件里内容是json=[{"PLC名称":"xx","PLC品牌":"西门子Siemens","IP":""},{"PLC名称":"yy","PLC品牌":"西门子Siemens","IP":""}] 读取到listview里显示,写一个案例;
时间: 2023-11-13 12:04:12 浏览: 145
C#读写西门子PLC数据例程源码
5星 · 资源好评率100%
以下是一个将ini文件中的json数据读取到listview中显示的C#案例:
```csharp
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
namespace IniFileDemo
{
public partial class Form1 : Form
{
[DllImport("kernel32")]
private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
private string iniFilePath = "config.ini"; // ini文件路径
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// 读取ini文件中的json数据
StringBuilder sb = new StringBuilder(1024);
GetPrivateProfileString("Section1", "json", "", sb, 1024, iniFilePath);
string jsonStr = sb.ToString();
// 将json数据转换为List<Dictionary<string, string>>类型
List<Dictionary<string, string>> dataList = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(jsonStr);
// 将数据显示在listview中
foreach (var data in dataList)
{
ListViewItem item = new ListViewItem(data["PLC名称"]);
item.SubItems.Add(data["PLC品牌"]);
item.SubItems.Add(data["IP"]);
listView1.Items.Add(item);
}
}
}
}
```
阅读全文