I am trying to use OleDB 4 to read some data in CSV files. I am using the following code, which I have copied from various sources that indicate it should work....
protected virtual string ConnectionString
{
get
{
return string.Format(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='text;HDR=Yes;FMT=Delimited'", _path);
}
}
public void ReadData()
{
using (OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT [Name] FROM SomeTable", ConnectionString))
{
using (DataTable table = new DataTable())
{
adapter.Fill(table);
foreach (DataRow row in table.Rows)
{
//Do something with the data
}
}
}
}
I am trying to test the code with a unit test, but I keep getting the following exception on the "adapter.Fill" line:
"The Microsoft Jet database engi开发者_JAVA百科ne cannot open the file ''. It is already opened exclusively by another user, or you need permission to view its data."
Please can anyone give me some clues to find out what the problem might be? The file is not opened by another application already. I have tried using a path under "AppDomain.CurrentDomain.BaseDirectory" as well as just a hard-coded path to a temporary folder, but whatever I try it gives me the same error.
In the connection string you must set Data Source
to the folder that contains the CSV file, then you have to SELECT * FROM your-file-name.csv
.
Here working (and tested) sample with a file located in F:\Temp\dummy.csv
:
var dir = @"F:\Temp";
var fn = "dummy.csv";
var cn = new OleDbConnection(
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"" + dir + "\";Extended Properties='text;HDR=Yes;FMT=Delimited(,)';");
cn.Open();
var cmd = new OleDbCommand("select * from [" + fn + "]", cn);
var rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Console.WriteLine(rdr[0] + " " + rdr[1]);
}
cn.Close();
精彩评论