有些文件需要用表格形式存储,方便修改,由此我写了按.csv格式存储和加载文件的代码,方便大家参考。
加载.csv格式的文件
public static List<List<string>> loadInformation(string fullPath)
{
List<List<string>> informationList = new List<List<string>>();
if (File.Exists(fullPath))//判断文件是否存在
{
StreamReader streamReader = new StreamReader(fullPath);//读取文件
string information = streamReader.ReadToEnd();//读取文件中的数据
string[] strArr = information.Split( '\n' );//按每一行读取相应的内容
for (int i = 1; i < strArr.Length - 1; i++)
{
List<string> singleInformation = new List<string>();
string[] arr = strArr[i].Split(',');//将每一行的信息按英文,划分
for (int j = 0; j < arr.Length; j++)
singleInformation.Add(arr[j]);
informationList.Add(singleInformation);
}
streamReader.Close();//关闭文件
}
else informationList = new List<List<string>> ();
return informationList;//返回的数据类型
}
保存为.csv格式的文件
public static void Save(string filePath, string fileName, string informationType, List<List<string>> informationList)
{
string FilePath = filePath + '/' + fileName + ".csv";
FileInfo file = new FileInfo(FilePath);
StreamWriter streamWriter = file.CreateText();//按文件路径和文件名创建对应的文件
if (File.Exists(FilePath))
{
streamWriter.WriteLine(informationType);
for (int i = 0; i < informationList.Count; i++)
{
for (int j = 0; j < informationList[i].Count; j++)
{
string singleInformation = " ";
if (j != informationList[i].Count - 1)
singleInformation = informationList[i][j] + ",";//将每一行内容写入文件
else
singleInformation = informationList[i][j] + "\n";//写入最后一个内容并换行
streamWriter.Write(singleInformation);
}
}
streamWriter.Close();//关闭文件
streamWriter.Dispose();
}
}