c#读取csv文件给出了无效的路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1458068/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 17:44:38  来源:igfitidea点击:

c# reading csv file gives not a valid path

c#csvoledb

提问by sean

I can't seem to read a .csv file using the following connection string:

我似乎无法使用以下连接字符串读取 .csv 文件:

var fileName = string.Format("{0}{1}", AppDomain.CurrentDomain.BaseDirectory, "Uploads\countrylist.csv");
string connectionString = string.Format(@"Provider=Microsoft.Jet.OLEDB.4.0; Data Source={0}; Extended Properties=""text;HDR=YES;FMT=Delimited""", fileName);
OleDbConnection oledbConn = new OleDbConnection(connectionString);
oledbConn.Open();

It gives the following error:

它给出了以下错误:

'D:\arrgh\arrgh\Uploads\countrylist.csv' is not a valid path. Make sure that the path name is spelled correctly and that you are connected to the server on which the file resides.

'D:\arrgh\arrgh\Uploads\countrylist.csv' 不是有效路径。确保路径名拼写正确,并且您已连接到文件所在的服务器。

I verified that the file is there. What is happening here?

我确认文件在那里。这里发生了什么?

采纳答案by sean

Ok, I dug a little further and it seems that my connection string is wrong. With CSV files, you don't specify the actual file name but the directory where it belongs, eg.

好吧,我挖了一点,似乎我的连接字符串是错误的。对于 CSV 文件,您不需要指定实际的文件名,而是指定它所属的目录,例如。

var fileName = string.Format("{0}{1}", AppDomain.CurrentDomain.BaseDirectory, "Uploads\");
string connectionString = string.Format(@"Provider=Microsoft.Jet.OLEDB.4.0; Data Source={0}; Extended Properties=""text;HDR=YES;FMT=Delimited""", fileName);
OleDbConnection oledbConn = new OleDbConnection(connectionString);
oledbConn.Open();
var cmd = new OleDbCommand("SELECT * FROM [countrylist.csv]", oledbConn);

And you specify the filename in the SelectCommand. What a strange way of doing it. It's working for me now.

然后在 SelectCommand 中指定文件名。多么奇怪的做法啊。它现在对我有用。

回答by Mitch Wheat

The way to combine paths and filenames is to use:

组合路径和文件名的方法是使用:

fullFilename = System.IO.Path.Combine(folderfilepath, Filename);

in your example:

在你的例子中:

var fileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Uploads\countrylist.csv");

回答by AaronLS

If the D drive is a mapped network drive then you may need to use the UNC path:

如果 D 驱动器是映射网络驱动器,则您可能需要使用 UNC 路径:

\computerName\shareName\path\

回答by Null

I had the same problem a few weeks ago trying to do some Office 2007 automation and spent too much time trying to fix it.

几周前,我在尝试执行一些 Office 2007 自动化时遇到了同样的问题,并花了太多时间试图修复它。

string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1;\"";

回答by Jay Riggs

I recommend you use a CSV parser rather than using the OLEDB data provider.

我建议您使用 CSV 解析器,而不是使用 OLEDB 数据提供程序。

Search and you'll find many (free) candidates. Here are a few that worked for me:

搜索,您会发现许多(免费)候选人。以下是一些对我有用的:

A portable and efficient generic parser for flat files(easiest to use, IMO)
A Fast CSV Reader(easy to use, great for large data sets)
FileHelperslibrary (flexible, includes code generators, bit of a learning curve)

用于平面文件的可移植且高效的通用解析器(最易于使用,IMO)
快速 CSV 阅读器(易于使用,非常适合大型数据集)
FileHelpers库(灵活,包括代码生成器,有点学习曲线)

Typically these will allow you to specify properties of your CSV (delimiter, header, text qualifier, etc.) and with a method call your CSV is dumped to a data structure of some sort, such as a DataTable or List<>.

通常,这些将允许您指定 CSV 的属性(分隔符、标题、文本限定符等),并通过调用方法将您的 CSV 转储到某种数据结构,例如 DataTable 或 List<>。

If you'll be working at all with CSV, it's worth checking out a CSV parser.

如果您将完全使用 CSV,那么值得查看 CSV 解析器。

回答by Daniel Pryden

If you're just trying to read a CSV file with C#, the easiest thing is to use the Microsoft.VisualBasic.FileIO.TextFieldParserclass. It's actually built into the .NET Framework, instead of being a third-party extension.

如果您只是想用 C# 读取 CSV 文件,最简单的方法是使用Microsoft.VisualBasic.FileIO.TextFieldParser类。它实际上内置于 .NET Framework 中,而不是第三方扩展。

Yes, it is in Microsoft.VisualBasic.dll, but that doesn't mean you can't use it from C# (or any other CLR language).

是的,它在 中Microsoft.VisualBasic.dll,但这并不意味着您不能在 C#(或任何其他 CLR 语言)中使用它。

Here's an example of usage, taken from the MSDN documentation:

下面是一个使用示例,取自MSDN 文档

Using MyReader As New _
Microsoft.VisualBasic.FileIO.TextFieldParser("C:\testfile.txt")
   MyReader.TextFieldType = FileIO.FieldType.Delimited
   MyReader.SetDelimiters(",")
   Dim currentRow As String()
   While Not MyReader.EndOfData
      Try
         currentRow = MyReader.ReadFields()
         Dim currentField As String
         For Each currentField In currentRow
            MsgBox(currentField)
         Next
      Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
      MsgBox("Line " & ex.Message & _
      "is not valid and will be skipped.")
      End Try
   End While
End Using

Again, this example is in VB.NET, but it would be trivial to translate it to C#.

同样,这个示例是在 VB.NET 中,但将其转换为 C# 是微不足道的。

回答by littlecodefarmer758

try this, A Fast CSV Reader, efficient CSV parser

试试这个,一个快速的 CSV 阅读器,高效的 CSV 解析器

CsvReader

CSV阅读器