使用 OleDB 读取 CSV 数据时出现文件访问错误
我正在尝试使用 OleDB 4 读取 CSV 文件中的一些数据。我正在使用以下代码,我从各种来源复制了该代码,表明它应该可以工作......
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
}
}
}
}
我正在尝试使用单元测试来测试代码,但我不断在“adapter.Fill”行上收到以下异常:
“Microsoft Jet 数据库引擎无法打开文件 ''。该文件已被其他用户以独占方式打开,或者您需要权限才能查看其数据。”
请问有人可以给我一些线索来找出问题所在吗?该文件尚未被其他应用程序打开。我尝试使用“AppDomain.CurrentDomain.BaseDirectory”下的路径以及临时文件夹的硬编码路径,但无论我尝试什么,它都会给我同样的错误。
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 engine 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在连接字符串中,您必须将
数据源
设置为包含 CSV 文件的文件夹,然后必须SELECT * FROM your-file-name.csv
。这里的工作(和测试)示例的文件位于
F:\Temp\dummy.csv
:In the connection string you must set
Data Source
to the folder that contains the CSV file, then you have toSELECT * FROM your-file-name.csv
.Here working (and tested) sample with a file located in
F:\Temp\dummy.csv
: