C# CSV文件读写

CSV是一种通用的、相对简单的文件格式,最广泛的应用是在程序之间转移表格数据,而这些程序本身是在不兼容的格式上进行操作的。那么,C#如何读取和写入csv格式文件呢?CSV数据格式并没有非常统一的标准 但是为了避免出错 我们在开发的时候统一格式是这样的:

"name","pwd","date"

"张三","123","2015-09-30"

接下来代码处理中默认格式都是这样的

为什么要用csv文件

这就涉及到数据互通的问题,有些程序支持的表格数据另一些程序并不见得支持,而csv格式的却被大多数的应用程序支持,所以在交换保存数据的时候是个不错的选择。

注意的点:

  • 文件处理完的时候一定记得关闭释放数据流 否则文件会被占用
  • csv并没有严格的标准,多人开发的时候必须规定好格式,统一开发 

一、DataTable数据写入CSV文件

 
  1. public static void SaveCSV(DataTable dt, string fullPath)//table数据写入csv

  2. {

  3. System.IO.FileInfo fi = new System.IO.FileInfo(fullPath);

  4. if (!fi.Directory.Exists)

  5. {

  6. fi.Directory.Create();

  7. }

  8. System.IO.FileStream fs = new System.IO.FileStream(fullPath, System.IO.FileMode.Create,

  9. System.IO.FileAccess.Write);

  10. System.IO.StreamWriter sw = new System.IO.StreamWriter(fs, System.Text.Encoding.UTF8);

  11. string data = "";

  12. for (int i = 0; i < dt.Columns.Count; i++)//写入列名

  13. {

  14. data += dt.Columns[i].ColumnName.ToString();

  15. if (i < dt.Columns.Count - 1)

  16. {

  17. data += ",";

  18. }

  19. }

  20. sw.WriteLine(data);

  21. for (int i = 0; i < dt.Rows.Count; i++) //写入各行数据

  22. {

  23. data = "";

  24. for (int j = 0; j < dt.Columns.Count; j++)

  25. {

  26. string str = dt.Rows[i][j].ToString();

  27. str = str.Replace("\"", "\"\"");//替换英文冒号 英文冒号需要换成两个冒号

  28. if (str.Contains(',') || str.Contains('"')

  29. || str.Contains('\r') || str.Contains('\n')) //含逗号 冒号 换行符的需要放到引号中

  30. {

  31. str = string.Format("\"{0}\"", str);

  32. }

  33. data += str;

  34. if (j < dt.Columns.Count - 1)

  35. {

  36. data += ",";

  37. }

  38. }

  39. sw.WriteLine(data);

  40. }

  41. sw.Close();

  42. fs.Close();

  43. }

二、读取CSV文件到DataTable

 
  1. public static DataTable OpenCSV(string filePath)//从csv读取数据返回table

  2. {

  3. System.Text.Encoding encoding = GetType(filePath); //Encoding.ASCII;//

  4. DataTable dt = new DataTable();

  5. System.IO.FileStream fs = new System.IO.FileStream(filePath, System.IO.FileMode.Open,

  6. System.IO.FileAccess.Read);

  7. System.IO.StreamReader sr = new System.IO.StreamReader(fs, encoding);

  8. //记录每次读取的一行记录

  9. string strLine = "";

  10. //记录每行记录中的各字段内容

  11. string[] aryLine = null;

  12. string[] tableHead = null;

  13. //标示列数

  14. int columnCount = 0;

  15. //标示是否是读取的第一行

  16. bool IsFirst = true;

  17. //逐行读取CSV中的数据

  18. while ((strLine = sr.ReadLine()) != null)

  19. {

  20. if (IsFirst == true)

  21. {

  22. tableHead = strLine.Split(',');

  23. IsFirst = false;

  24. columnCount = tableHead.Length;

  25. //创建列

  26. for (int i = 0; i < columnCount; i++)

  27. {

  28. DataColumn dc = new DataColumn(tableHead[i]);

  29. dt.Columns.Add(dc);

  30. }

  31. }

  32. else

  33. {

  34. aryLine = strLine.Split(',');

  35. DataRow dr = dt.NewRow();

  36. for (int j = 0; j < columnCount; j++)

  37. {

  38. dr[j] = aryLine[j];

  39. }

  40. dt.Rows.Add(dr);

  41. }

  42. }

  43. if (aryLine != null && aryLine.Length > 0)

  44. {

  45. dt.DefaultView.Sort = tableHead[0] + " " + "asc";

  46. }

  47. sr.Close();

  48. fs.Close();

  49. return dt;

  50. }

  51. /// 给定文件的路径,读取文件的二进制数据,判断文件的编码类型

  52. /// <param name="FILE_NAME">文件路径</param>

  53. /// <returns>文件的编码类型</returns>

  54. public static System.Text.Encoding GetType(string FILE_NAME)

  55. {

  56. System.IO.FileStream fs = new System.IO.FileStream(FILE_NAME, System.IO.FileMode.Open,

  57. System.IO.FileAccess.Read);

  58. System.Text.Encoding r = GetType(fs);

  59. fs.Close();

  60. return r;

  61. }

  62. /// 通过给定的文件流,判断文件的编码类型

  63. /// <param name="fs">文件流</param>

  64. /// <returns>文件的编码类型</returns>

  65. public static System.Text.Encoding GetType(System.IO.FileStream fs)

  66. {

  67. byte[] Unicode = new byte[] { 0xFF, 0xFE, 0x41 };

  68. byte[] UnicodeBIG = new byte[] { 0xFE, 0xFF, 0x00 };

  69. byte[] UTF8 = new byte[] { 0xEF, 0xBB, 0xBF }; //带BOM

  70. System.Text.Encoding reVal = System.Text.Encoding.Default;

  71. System.IO.BinaryReader r = new System.IO.BinaryReader(fs, System.Text.Encoding.Default);

  72. int i;

  73. int.TryParse(fs.Length.ToString(), out i);

  74. byte[] ss = r.ReadBytes(i);

  75. if (IsUTF8Bytes(ss) || (ss[0] == 0xEF && ss[1] == 0xBB && ss[2] == 0xBF))

  76. {

  77. reVal = System.Text.Encoding.UTF8;

  78. }

  79. else if (ss[0] == 0xFE && ss[1] == 0xFF && ss[2] == 0x00)

  80. {

  81. reVal = System.Text.Encoding.BigEndianUnicode;

  82. }

  83. else if (ss[0] == 0xFF && ss[1] == 0xFE && ss[2] == 0x41)

  84. {

  85. reVal = System.Text.Encoding.Unicode;

  86. }

  87. r.Close();

  88. return reVal;

  89. }

  90. /// 判断是否是不带 BOM 的 UTF8 格式

  91. /// <param name="data"></param>

  92. /// <returns></returns>

  93. private static bool IsUTF8Bytes(byte[] data)

  94. {

  95. int charByteCounter = 1;  //计算当前正分析的字符应还有的字节数

  96. byte curByte; //当前分析的字节.

  97. for (int i = 0; i < data.Length; i++)

  98. {

  99. curByte = data[i];

  100. if (charByteCounter == 1)

  101. {

  102. if (curByte >= 0x80)

  103. {

  104. //判断当前

  105. while (((curByte <<= 1) & 0x80) != 0)

  106. {

  107. charByteCounter++;

  108. }

  109. //标记位首位若为非0 则至少以2个1开始 如:110XXXXX...........1111110X 

  110. if (charByteCounter == 1 || charByteCounter > 6)

  111. {

  112. return false;

  113. }

  114. }

  115. }

  116. else

  117. {

  118. //若是UTF-8 此时第一位必须为1

  119. if ((curByte & 0xC0) != 0x80)

  120. {

  121. return false;

  122. }

  123. charByteCounter--;

  124. }

  125. }

  126. if (charByteCounter > 1)

  127. {

  128. throw new Exception("非预期的byte格式");

  129. }

  130. return true;

  131. }

三、修改文件名称

我们需要保存历史数据 或者实时的知道那个文件被修改 可以通过改变文件的名称 如加上当天的日期等等。

 
  1. public static bool ChangeFileName(string OldPath, string NewPath)

  2. {

  3. bool re = false;

  4. try

  5. {

  6. if (File.Exists(OldPath))

  7. {

  8. File.Move(OldPath, NewPath);

  9. re = true;

  10. }

  11. }

  12. catch

  13. {

  14. re = false;

  15. }

  16. return re;

  17. }

四、CSV文件的数据写入

直接在网页表单提交数据保存在csv文件中 直接写入文件

 
  1. public static bool SaveCSV(string fullPath,string Data)

  2. {

  3. bool re = true;

  4. try

  5. {

  6. FileStream FileStream = new FileStream(fullPath, FileMode.Append);

  7. StreamWriter sw = new StreamWriter(FileStream, System.Text.Encoding.UTF8);

  8. sw.WriteLine(Data);

  9. //清空缓冲区

  10. sw.Flush();

  11. //关闭流

  12. sw.Close();

  13. FileStream.Close();

  14. }

  15. catch

  16. {

  17. re = false;

  18. }

  19. return re;

  20. }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值