csv文件写入 key value 读取 c#
时间: 2024-11-15 15:24:20 浏览: 38
在C#中,使用`StreamWriter`可以写入CSV文件,而读取文件则可以使用`StreamReader`配合`Split`函数。以下是简单的操作过程:
### 写入CSV文件
```csharp
using System;
using System.IO;
class Program
{
public static void WriteToCsv(string filePath, Dictionary<string, string> data)
{
try
{
using (StreamWriter writer = new StreamWriter(filePath))
{
// 写入表头
writer.WriteLine(string.Join(",", data.Keys));
// 遍历字典并写入每条记录
foreach (KeyValuePair<string, string> pair in data)
{
writer.WriteLine($"{pair.Key},{pair.Value}");
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Error writing to CSV file: {ex.Message}");
}
}
}
```
在这个函数中,我们先写入字典的所有键作为表头,然后再遍历字典写入每个键值对。
### 读取CSV文件
```csharp
using System;
using System.Collections.Generic;
using System.IO;
class Program
{
public static Dictionary<string, string> ReadFromCsv(string filePath)
{
try
{
Dictionary<string, string> data = new Dictionary<string, string>();
using (StreamReader reader = new StreamReader(filePath))
{
// 跳过表头
reader.ReadLine();
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
string[] values = line.Split(',');
data[values[0]] = values[1]; // 将键值对存入字典
}
}
return data;
}
catch (Exception ex)
{
Console.WriteLine($"Error reading from CSV file: {ex.Message}");
return null; // 返回null表示失败
}
}
}
```
这里读取文件时,我们同样跳过表头,然后按行分割数据并存储到字典中。
阅读全文
相关推荐


















