c# reading csv file gives not a valid path

前端 未结 7 1889
Happy的楠姐
Happy的楠姐 2020-12-05 07:04

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

var fileName = string.Format(\"{0}{1}\", AppDomain.CurrentDomain.BaseDirectory, \"Up         


        
相关标签:
7条回答
  • 2020-12-05 07:34

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

    \\computerName\shareName\path\
    
    0 讨论(0)
  • 2020-12-05 07:38

    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.

    string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1;\"";
    
    0 讨论(0)
  • 2020-12-05 07:43

    try this, A Fast CSV Reader, efficient CSV parser

    CsvReader

    0 讨论(0)
  • 2020-12-05 07:46

    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.

    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.

    0 讨论(0)
  • 2020-12-05 07:46

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

    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)
    FileHelpers library (flexible, includes code generators, bit of a learning curve)

    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<>.

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

    0 讨论(0)
  • 2020-12-05 07:57

    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");
    
    0 讨论(0)
提交回复
热议问题