//读写文件
public class ReadWriteFile
{
public static List<string> ReadFile(string path)
{
try
{
using (FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read))
{
List<string> list = new List<string>();
using (StreamReader streamReader = new StreamReader(fileStream))
{
while (!streamReader.EndOfStream)
{
list.Add(streamReader.ReadLine());
}
return list;
}
}
}
catch (Exception)
{
throw new Exception("read error!");
}
}
public static void WriteFile(string path, List<string> list)
{
try
{
using (FileStream fileStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
{
using (StreamWriter streamWriter = new StreamWriter(fileStream))
{
for (int i = 0; i < list.Count; i++)
{
streamWriter.WriteLine(list[i]);
}
}
}
}
catch (Exception)
{
throw new Exception("write error!");
}
}
}
//列表和表格转换
public static class ListViewConvert
{
public static void ListToView(List<string> list, DataGridView dataGridView)
{
dataGridView.Columns.Clear();
string[] s = list[0].Split(',');
for (int i = 0; i < s.Length; i++)
{
dataGridView.Columns.Add(s[i], s[i]);
}
for (int i = 0; i < list.Count - 1; i++)
{
dataGridView.Rows.Add();
s = list[i + 1].Split(',');
for (int j = 0; j < s.Length; j++)
{
dataGridView.Rows[i].Cells[j].Value = s[j];
}
}
}
public static List<string> ViewToList(DataGridView dataGridView)
{
List<string> list = new List<string>();
string str = dataGridView.Columns[0].Name.ToString();
for (int i = 1; i < dataGridView.Columns.Count; i++)
{
str = str + "," + dataGridView.Columns[i].Name.ToString();
}
list.Add(str);
for (int i = 0; i < dataGridView.Rows.Count - 1; i++)
{
str = dataGridView.Rows[i].Cells[0].Value.ToString();
for (int j = 1; j < dataGridView.Columns.Count; j++)
{
str = str + "," + dataGridView.Rows[i].Cells[j].Value.ToString();
}
list.Add(str);
}
return list;
}
}
//界面显示
private void btnRead_Click(object sender, EventArgs e)
{
try
{
List<string> list = ReadWriteFile.ReadFile(@"C:\Users\12072\Desktop\22.csv");
ListViewConvert.ListToView(list, dataGridView1);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void btnWrite_Click(object sender, EventArgs e)
{
try
{
List<string> list = ListViewConvert.ViewToList(dataGridView1);
ReadWriteFile.WriteFile(@"C:\Users\12072\Desktop\33.csv", list);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}