一、txt文件
1. 写入txt文件
File.AppendAllText(@“C:\test.txt”, text);
File.WriteAllText(@“C:\test.txt”, text);
2. 读取txt文件
string str = File.ReadAllText(@“C:\test.txt”);
3. 获取当前程序的运行目录
string path = Directory.GetCurrentDirectory();
二、 创建文件夹
Directory.Exists(path);
Directory.CreateDirectory(path);
三、csv操作
1. 写入csv文件
tring path = @”C:\data.csv”;
using(StreamWriter sw = new StreamWriter(path, true, Encoding.Default)){
StringBuilder sb = new StringBuilder();
sb.Append(textBox1.Text).Append(textBox2.Text).Append(textBox3.Text)
sw.WriteLine(sb);
sw.Close();
sw.Dispose();
}
四、csv封装
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IcCogFrameGrabber连相机
{
public class FileOperate
{
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";
if (!File.Exists(fileName))
{
FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs, Encoding.Default);
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";
StreamReader sr = new StreamReader(fileName, Encoding.Default);
string str = sr.ReadToEnd();
return str;
}
}
}
五、自创csv写入方法
string data = "1,2,3,4,5\n";
File.AppendAllText(path + "\\data.csv", data);
MessageBox.Show("111");