
C# 中的 CSV 文件操作(包括写入、读取和修改)
5星
- 浏览量: 0
- 大小:None
- 文件类型:None
简介:
本教程详细介绍了如何在C#编程语言中进行CSV文件的操作,涵盖写入、读取及修改等核心功能,帮助开发者高效处理数据。
一、将DataTable数据写入CSV文件
```csharp
public static void SaveCSV(DataTable dt, string fullPath)
{
System.IO.FileInfo fi = new System.IO.FileInfo(fullPath);
if (!fi.Directory.Exists)
{
fi.Directory.Create();
}
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(fullPath))
{
// 写入表头
for (int i = 0; i < dt.Columns.Count; i++)
{
sw.Write(dt.Columns[i]);
if (i < dt.Columns.Count - 1)
sw.Write(,);
}
sw.WriteLine();
// 写入数据行
foreach (DataRow dr in dt.Rows)
{
for (int i = 0; i < dt.Columns.Count; i++)
{
if (!Convert.IsDBNull(dr[i]))
{
string data = dr[i].ToString();
data = data.Replace(,, ;); // 避免逗号导致数据错误
sw.Write(data);
}
if (i < dt.Columns.Count - 1)
sw.Write(,);
}
sw.WriteLine();
}
}
}
```
注意:代码中缺少了`System.IO.FileMode`的参数。完整的调用方式应该为 `new System.IO.FileStream(fullPath, System.IO.FileMode.Create)`,但根据上下文信息补充完整该部分可能需要更多的具体细节来确保正确性。
全部评论 (0)


