CVS是一个轻量级的数据库,文本之间是以 逗号分隔的。结合泛型,读取此种文件的方式如下:
代码
public List<Dictionary<string, string>> GetData(string filePath, out List<string> Column)
{
Column = new List<string>();
List<Dictionary<string, string>> Data = new List<Dictionary<string, string>>();
string strLine = "";
string[] strArray;
StreamReader sr = new StreamReader(filePath);
strLine = sr.ReadLine();
if (strLine == null || strLine == "")
{
return new List<Dictionary<string, string>>();
}
strArray = strLine.Split(',');
foreach (string item in strArray)
{
Column.Add(item);
}
strLine = sr.ReadLine();
while (strLine != null)
{
strArray = strLine.Split(',');
Dictionary<string, string> dict = new Dictionary<string, string>();
for (int i = 0; i < Column.Count; i++)
{
dict.Add(Column[i], strArray[i]);
}
Data.Add(dict);
strLine = sr.ReadLine();
}
sr.Close();
return Data;
}
调用方法如下:
List<string> Column;
List<Dictionary<string, string>> Date = GetData(this.textBox1.Text.Trim(), out Column);
string str = "";
foreach (Dictionary<string, string> item in Date)
{
foreach (string item1 in Column)
{
str += item[item1] + " ";
}
str += Environment.NewLine;
}
this.textBox2.Text = str;