Search code examples
c#asp.netdotnetnukefilehelpers

Using FileHelpers to read CSV file from asp.net file upload


I'm working on an ASP.NET Webforms C# application. I need to have a CSV file uploaded to server and contents read and saved to database. I read somewhere that FileHelpers may be used for reading csv files but I haven't seen any example dealing with a HttpPostedFile. Anybody has any experience using filehelpers with file upload?

I'm open to alternative methods too. Thanks.


Solution

  • Here is a sample to get you started.

    using FileHelpers;
    
    // First declare the record class
    
    [Delimitedrecord("|")]
    public class SampleType
    {
        public string Field1;
        public int    Field2;
    }
    
    
    public void ReadExample(HttpPostedFile file)
    {
        FileHelperEngine engine = new FileHelperEngine(typeof(SampleType));
    
        SampleType[] records;    
    
        records = (SampleType[]) engine.ReadStream(
                             new StreamReader(file.InputStream), Int32.MaxValue);
    
        // Now "records" array contains all the records in the
        // uploaded file and can be acceded like this:
    
        int sum = records[0].Field2 + records[1].Field2;
    }