public class CsvController
{
static CsvController csv;
public List<string[]> arrayData;
private CsvController() //单例,构造方法为私有
{
arrayData = new List<string[]>();
}
public static CsvController GetInstance() //单例方法获取对象
{
if (csv == null)
{
csv = new CsvController();
}
return csv;
}
public void loadFile(string path, string fileName)
{
arrayData.Clear();
StreamReader sr = null;
try
{
string file_url = path + "//" + fileName; //根据路径打开文件
sr = File.OpenText(file_url);
}
catch
{
return;
}
string line;
while ((line = sr.ReadLine()) != null) //按行读取
{
arrayData.Add(line.Split(',')); //每行逗号分隔,split()方法返回 string[]
}
sr.Close();
sr.Dispose();
}
public string[] GetColData(int col)
{
string[] colArray = new string[arrayData.Count];
for (int i = 0; i < arrayData.Count; i++)
{
colArray[i] = getString(i, col);
}
return colArray;
}
public string getString(int row, int col)
{
return arrayData[row][col];
}
public int getInt(int row, int col)
{
return int.Parse(arrayData[row][col]);
}
}
使用
CsvController.GetInstance().loadFile("F:", "Test.csv");
string[] ColData = CsvController.GetInstance().GetColData(0);