##1. csv文件的操作
class CSVHelper
{
//文件路径
private string pathName;
//list保存数据
private List<string> msg;
public CSVHelper(string path)
{
pathName = path;
msg = new List<string>();
}
#region Method
/// <summary>
/// 写入数据
/// </summary>
/// <param name="data"></param>
public void writeData(string data)
{
using (StreamWriter writer = new StreamWriter(pathName,true))
{
writer.WriteLine($"{data}");
}
}
/// <summary>
/// 读取全部内容
/// </summary>
public List<string> readData()
{
using(StreamReader reader = new StreamReader(pathName))
{
// 读取文件的每一行
while (!reader.EndOfStream)
{
// 读取一行数据
string line = reader.ReadLine();
msg.Add(line);
}
}
return msg;
}
/// <summary>
/// 读取指定行
/// </summary>
/// <param name="num"></param>
/// <returns></returns>
public List<string> readLineData(int num)
{
List<string> str = new List<string>();
using (StreamReader reader = new StreamReader(pathName))
{
int sum = 0;
// 读取文件的每一行
while (!reader.EndOfStream)
{
sum++;
string line = reader.ReadLine();
if (sum == num)
{
str.Add(line);
}
}
}
return str;
}
/// <summary>
/// 删除指定行
/// </summary>
/// <param name="num"></param>
public void deleteLineData(int num)
{
List<string> str = new List<string>();
using (StreamReader reader = new StreamReader(pathName))
{
// 读取文件的每一行
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
str.Add(line);
}
}
if(num >= 1 && num <= str.Count())
{
str.RemoveAt(num-1);
}
using(StreamWriter writer = new StreamWriter(pathName))
{
foreach (string line in str)
{
writer.WriteLine(line);
}
}
}
/// <summary>
/// 修改数据
/// </summary>
/// <param name="str"></param>
/// <param name="num"></param>
public void updateData(string str,int num)
{
List<string> str1 = new List<string>();
using (StreamReader reader = new StreamReader(pathName))
{
// 读取文件的每一行
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
str1.Add(line);
}
}
if (num >= 1 && num <= str1.Count())
{
str1[num - 1] = str;
}
using (StreamWriter writer = new StreamWriter(pathName))
{
foreach (string line in str1)
{
writer.WriteLine(line);
}
}
}
#endregion
}