简体   繁体   English

使用OleDB读取CSV数据时出现文件访问错误

[英]File Access Error using OleDB to read CSV data

I am trying to use OleDB 4 to read some data in CSV files. 我正在尝试使用OleDB 4读取CSV文件中的一些数据。 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: 我正在尝试使用单元测试来测试代码,但是我在“ adapter.Fill”行中不断收到以下异常:

"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." “ Microsoft Jet数据库引擎无法打开文件”。该文件已经由另一个用户专门打开,或者您需要查看它的数据的权限。”

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. 我试过使用“ AppDomain.CurrentDomain.BaseDirectory”下的路径,以及到临时文件夹的硬编码路径,但是无论如何,它都会给我同样的错误。

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 . 在连接字符串中,必须将“ Data Source设置为包含CSV文件的文件夹,然后必须SELECT * FROM your-file-name.csv

Here working (and tested) sample with a file located in F:\\Temp\\dummy.csv : 在这里使用(并经过测试)带有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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM