API
cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CSV
{
public class CSVApi
{
public void SaveData(string data, string result)
{
string path = Directory.GetCurrentDirectory() + "\\Data";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
//string fileName = path + "\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".csv";
string fileName = $"{path}\\{DateTime.Now.ToString("yyyy-MM-dd")}.csv";
if (!File.Exists(fileName))
{
//创建文件流,传入文件路径,创建并写入
FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write);
//Encoding.Default 编码格式 允许写入中文内容
StreamWriter sw = new StreamWriter(fs, Encoding.Default);
//创建StringBuilder类型追加写入信息
StringBuilder sb = new StringBuilder();
sb.Append("时间").Append(",").Append("Data").Append(",").Append("Result");
sw.WriteLine(sb);
sw.Close();
sw.Dispose();
fs.Close();
fs.Dispose();
}
using (StreamWriter sw2 = new StreamWriter(fileName, true, Encoding.Default))
{
StringBuilder sb = new StringBuilder();
sb.Append(DateTime.Now.ToString("HH-mm-ss")).Append(",").Append(data).Append(",").Append(result);
sw2.WriteLine(sb);
}
}
public string ReadData()
{
string path = Directory.GetCurrentDirectory() + "\\Data";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
//string fileName = path + "\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".csv";
string fileName = $"{path}\\{DateTime.Now.ToString("yyyy-MM-dd")}.csv";
StreamReader sr = new StreamReader(fileName, Encoding.Default);
string str = sr.ReadToEnd();
return str;
}
}
}
调用
cs
using CSV;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CSV文件读写
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
CSVApi cSVApi = new CSVApi();
private void button1_Click(object sender, EventArgs e)
{
cSVApi.SaveData("张三","李四");
}
private void button2_Click(object sender, EventArgs e)
{
string value = cSVApi.ReadData();
MessageBox.Show(value);
}
}
}