Search code examples
c#csvhelper

CsvHelper.CsvRead returns nothing


My first time using CSVHelper.

I have a simple CSV file like this:

a,b,c
1,2,3
4,5,6
7,8,9

When I try to read it using this code:

using (var reader = new StreamReader(@"e:\a.csv"))
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
    // Do any configuration to `CsvReader` before creating CsvDataReader.
    using (var dr = new CsvDataReader(csv))
    {
        var dt = new DataTable();
        dt.Load(dr);
    }
}

csv returns nothing:

{CsvHelper.CsvReader}
    ColumnCount: 0
    Configuration: {CsvConfiguration { AllowComments = False, BadDataFound = CsvHelper.BadDataFound, BufferSize = 4096, CacheFields = False, Comment = #, CountBytes = False, CultureInfo = , Delimiter = ,, DetectDelimiter = False, DetectDelimiterValues = System.String[], DetectColumnCountChanges = False, DynamicPropertySort = , Encoding = System.Text.UTF8Encoding, Escape = ", ExceptionMessagesContainRawData = True, GetConstructor = CsvHelper.GetConstructor, GetDynamicPropertyName = CsvHelper.GetDynamicPropertyName, HasHeaderRecord = True, HeaderValidated = CsvHelper.HeaderValidated, IgnoreBlankLines = True, IgnoreReferences = False, IncludePrivateMembers = False, InjectionCharacters = System.Char[], InjectionEscapeCharacter =  , IsNewLineSet = False, LeaveOpen = False, LineBreakInQuotedFieldIsBadData = False, MemberTypes = Properties, MissingFieldFound = CsvHelper.MissingFieldFound, Mode = RFC4180, NewLine = 
, PrepareHeaderForMatch = CsvHelper.PrepareHeaderForMatch, ProcessFieldBufferSize = 1024, Quote = ", ReadingExceptionOccurred = CsvHelper.ReadingExceptionOccurred, ReferenceHeaderPrefix = , SanitizeForInjection = False, ShouldQuote = CsvHelper.ShouldQuote, ShouldSkipRecord = CsvHelper.ShouldSkipRecord, ShouldUseConstructorParameters = CsvHelper.ShouldUseConstructorParameters, TrimOptions = None, UseNewObjectForNullReferenceMembers = True, WhiteSpaceChars = System.Char[] }}
    Context: {CsvHelper.CsvContext}
    CurrentIndex: -1
    HeaderRecord: null
    Parser: {CsvHelper.CsvParser}

What is the problem? I cannot figure it out.


Solution

  • Test the code below I think the problem is how to open the file with StreamReader

    using (var streamReader = File.OpenText(path))
    {
       using (var csvReader = new CsvReader(streamReader, CultureInfo.CurrentCulture))
       {
           using (var dr = new CsvDataReader(csvReader))
           {
               var dt = new DataTable();
               dt.Load(dr);
           }
       }
    }