摘要在C#中,我們可以使用 正文CSV文件操作通用類public class CsvFile { private string filePath; private char delimiter;
public CsvFile(string filePath, char delimiter = ',') { this.filePath = filePath; this.delimiter = delimiter; }
public List<string[]> ReadAll(System.Text.Encoding encoding) { List<string[]> data = new List<string[]>();
try { using (StreamReader reader = new StreamReader(filePath, encoding) { while (!reader.EndOfStream) { string line = reader.ReadLine(); string[] values = line.Split(delimiter); data.Add(values); } } } catch (Exception ex) { Console.WriteLine('Error: ' + ex.Message); }
return data; }
public void WriteAll(List<string[]> data) { try { using (StreamWriter writer = new StreamWriter(filePath)) { foreach (string[] values in data) { string line = string.Join(delimiter.ToString(), values); writer.WriteLine(line); } } } catch (Exception ex) { Console.WriteLine('Error: ' + ex.Message); } } }
上述代碼定義了一個(gè) 使用CSV文件操作通用類
如是需要用Gb2312在Core下需要先安裝以下包 上述代碼演示了如何使用 |
|