1. 建立DataTable 类型
DataTable my_accurdt;
my_accurdt = new DataTable(DateTime.Now.ToString("yMMddHHmm") + "_AccurData");
2. 创建DataTable的列和行
//列
my_accurdt.Columns.Add(new DataColumn("Oder", typeof(int)));
my_accurdt.Columns.Add(new DataColumn("TimeStamp", typeof(string)));
//行
DataRow my_rows = my_accurdt.NewRow();
my_rows["Oder"] = dataTableOrder;
my_rows["TimeStamp"] = DateTime.Now.ToString("yMMddHHmm");
my_accurdt.Rows.Add(my_rows);
3. 把DataTable显示在WinForm的dataGridView控件中
Accur_table_dataGridView.DataSource = my_accurdt;
4. 创建写入CSV文件方法
//write function
public void writeDataCSV(string file_path, DataTable my_dt)
{
FileStream my_filestream;
StreamWriter my_streamwriter;
string my_data = null;
if (!File.Exists(file_path))
{
my_filestream = new FileStream(file_path, FileMode.Create, FileAccess.Write);
my_streamwriter = new StreamWriter(my_filestream, Encoding.UTF8);
//write columns name
for (int i = 0; i < my_dt.Columns.Count; i++)
{
my_data += my_dt.Columns[i].ColumnName.ToString();
if (i < my_dt.Columns.Count - 1)
{
my_data += ",";
}
}
my_streamwriter.WriteLine(my_data);
}
else
{
my_filestream = new FileStream(file_path, FileMode.Append, FileAccess.Write);
my_streamwriter = new StreamWriter(my_filestream, Encoding.UTF8);
}
//write rows
for (int i = 0; i < my_dt.Rows.Count; i++)
{
my_data = null;
for (int j = 0; j < my_dt.Columns.Count; j++)
{
my_data += my_dt.Rows[i][j].ToString();
if (j < my_dt.Columns.Count - 1)
{
my_data += ",";
}
}
my_streamwriter.WriteLine(my_data);
}
my_streamwriter.Close();
my_filestream.Close();
}
5. 创建读出CSV文件方法
//read function
public DataTable readDataCSV(string file_path)
{
DataTable my_dt = new DataTable();
FileStream my_filestream = new FileStream(file_path, FileMode.Open, FileAccess.Read);
StreamReader my_streamreader = new StreamReader(my_filestream, Encoding.UTF8);
string my_strLine = null;
string[] my_arrayLine = null;
bool isFirst = true;
int my_dtColumns = 0;
while ((my_strLine = my_streamreader.ReadLine()) != null)
{
my_strLine = my_strLine.Trim();
my_arrayLine = my_strLine.Split(',');
if (isFirst)
{
my_dtColumns = my_arrayLine.Length;
for (int i = 0; i < my_dtColumns; i++)
{
my_dt.Columns.Add(my_arrayLine[i]);
}
isFirst = false;
}
else
{
DataRow my_datarow = my_dt.NewRow();
for (int j = 0; j < my_dtColumns; j++)
{
if (my_arrayLine.Length > j)
{
my_datarow[j] = my_arrayLine[j];
}
}
my_dt.Rows.Add(my_datarow);
}
}
my_streamreader.Close();
my_filestream.Close();
return my_dt;
}
6. 创建文件保存路径选择框
//file storage path
public string SelectFolderPath()
{
string my_folderpath = string.Empty;
FolderBrowserDialog my_folderbrowser = new FolderBrowserDialog();
DialogResult my_result = my_folderbrowser.ShowDialog();
if (my_result == DialogResult.OK)
{
my_folderpath = my_folderbrowser.SelectedPath;
return my_folderpath;
}
else
{ return string.Empty; }
}
标签:string,C#,读出,filestream,new,dt,CSV,my,DataTable
From: https://www.cnblogs.com/xiacuncun/p/18177610