Reading a CSV
2012-03-23 by
private Dictionary<string, string> GetCSVAddresses(string path)
{
//create string dictionary
Dictionary<string, string> ret = new Dictionary<string, string>();
string full = System.IO.Path.GetFullPath(path);
string file = System.IO.Path.GetFileName(full);
string dir = System.IO.Path.GetDirectoryName(full);
//create the "database" connection string
//Ignore all of the column headers
string connString = "Provider=Microsoft.Jet.OLEDB.4.0;"
+ "Data Source=\"" + dir + "\\\";"
+ "Extended Properties=\"text;HDR=No;FMT=Delimited\"";
//create the database query
string query = "SELECT * FROM " + file;
System.Data.OleDb.OleDbConnection con = new System.Data.OleDb.OleDbConnection(connString);
System.Data.OleDb.OleDbDataReader reader;
//create an OleDbDataAdapter to execute the query
System.Data.OleDb.OleDbCommand com = new System.Data.OleDb.OleDbCommand(query, con);
con.Open();
reader = com.ExecuteReader();
//load string dictionary where column 1 is the key and column 2 is the value
while (reader.Read())
{
string key = reader[0].ToString();
string val = reader[1].ToString();
if (ret.ContainsKey(key))
ret[key] = val;
else
ret.Add(key, val);
}
con.Close();
return ret;
}