C#简单的操作csv文件

csv又名逗号文件,可以当作不是表格,而是逗号隔开的文本,简单的两个写入方法:

一:

private string csvFilePath = "D:\\Log\\csv\\";
private string csvTitle =
"SysTime" + "," + "Msg1" + "," + "Msg2" + "," +
"Msg3" + "\r\n";
private void button4_Click(object sender, EventArgs e)
{
string writeData = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "," + 1 + "," +2 + "," +3 + "\r\n";

string fileName = DateTime.Now.ToString("yyyy-MM-dd") + ".csv";
WriteTxtFile(csvFilePath + fileName, writeData);
}
private bool WriteTxtFile(string cscFile, string msg)
{
if (!File.Exists(cscFile)) NewCsvFile(cscFile); //判断文件是否存在,不存在则新建,按日期
try
{
using (FileStream fileStream = new FileStream(cscFile, FileMode.Open, FileAccess.Write)) // 写入文件
{
StreamWriter streamWriter = new StreamWriter(fileStream);
streamWriter.BaseStream.Seek(0, SeekOrigin.End); // 在csv末尾写入
streamWriter.Write(msg); // 写入csv文件内容
streamWriter.Flush();
streamWriter.Close();
fileStream.Close();
}
return true;
}
catch { return false; }
}
private void NewCsvFile(string csvFile)
{
string path = csvFile.Substring(0, csvFile.LastIndexOf("\\"));
if (!Directory.Exists(path)) Directory.CreateDirectory(path); //判断路径是否存在,不存在则创建
if (!File.Exists(csvFile)) //判断文件是否存在,不存在则创建
{
using (FileStream fileStream = new FileStream(csvFile, FileMode.Create, FileAccess.Write))
{
StreamWriter streamWriter = new StreamWriter(fileStream);
streamWriter.BaseStream.Seek(0, SeekOrigin.End); // 在csv末尾写入
streamWriter.Write(csvTitle); // 写入csv文件表头
streamWriter.Flush();
streamWriter.Close();
fileStream.Close();
}
}
}

 

二:

StringBuilder csvdata = new StringBuilder();
private void button9_Click(object sender, EventArgs e)
{
string savedatepath = @"D:\Log\csv";
string savedatename = string.Format(@"{0}.csv", DateTime.Now.ToString("yyyyMMdd"));
string savedatefile = string.Format(@"{0}\{1}", savedatepath, savedatename);
if (!File.Exists(savedatefile))
{
csvdata.Append(string.Format("{0},{1},{2}", "Time", "Barde", "Data"));
SaveDataToLocal(savedatepath, savedatename, csvdata.ToString());
csvdata.Clear();
}
csvdata.Append(string.Format("{0},{1},{2}", DateTime.Now.ToString("yyyyMMdd"), "111", "222"));
SaveDataToLocal(savedatepath, savedatename, csvdata.ToString());
csvdata.Clear();
}

private string SaveDataToLocal(string dirpath, string filename, string data) // save data to local path
{
string rtn = "";
string filePath = null;
filePath = string.Format(@"{0}\{1}", dirpath, filename);
try
{
DirectoryInfo dirpathinfo = new DirectoryInfo(dirpath);
if (!dirpathinfo.Exists)
{
dirpathinfo.Create();
}
FileStream fs = new FileStream(filePath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
StreamWriter writer = new StreamWriter(fs, Encoding.ASCII);//这里ASCII码输出CSV使用,但txt文件最好用UTF-8,因为汉字不用ASCII码
writer.WriteLine(data);
writer.Close();
fs.Close();
}
catch (Exception ex)
{
rtn = ex.Message.ToString();
}
return rtn;
}

 

熟练后可以用二元数组或者数据库写入,后续npio和调用有时间在更新~

posted @ 2020-09-08 22:07  SHW03  阅读(2824)  评论(0编辑  收藏  举报