You must Sign In to post a response.
  • Category: .NET

    Windows/Desktop application that automatically reads a CSV file from my local directory,c#

    Hi,
    I want to write a small windows/desktop application in C#, that basically works like this

    If I click a button i want it to read and loop through a csv file that is stored on my local computer folder.

    Your help will be greatly appreciated.
  • #768774
    Hi Spha,

    Refer below sample code.

    public DataTable ReadCSV(string inputPath)
    {
    try
    {
    using (CsvReader csv = new CsvReader(new StreamReader(inputPath), true))
    {
    dtCSV = ReadHeaders(csv);

    while (csv.ReadNextRecord())
    {
    DataRow drcsv = dtCSV.NewRow();
    for (int i = 0; i < dtCSV.Columns.Count; i++)
    {
    drcsv[i] = dtCSV.Columns[i].ToString();
    }

    dtCSV.Rows.Add(drcsv);
    dtCSV.AcceptChanges();
    }
    }
    }
    catch (Exception ex)
    {
    throw;
    }
    return dtCSV;
    }


    Read below article to know more about how to read csv file.

    http://www.dotnetspider.com/resources/46438-Read-and-Write-CSV-in-C.aspx

    Hope this helps you....

    --------------------------------------------------------------------------------
    Give respect to your work, Instead of trying to impress your boss.

    N@veen
    Blog : http://naveens-dotnet.blogspot.in/

  • #768775

    Hai Spha,
    As per your requirements, you can use the C# code to read the file using the delimiter which is inside the local folder.
    Once you read the file using line by line, you can get all the values and can stored them in the table/data-table.
    You can get the code snippet from the below links:

    http://stackoverflow.com/questions/5282999/reading-csv-file-and-storing-values-into-an-array
    http://stackoverflow.com/questions/3507498/reading-csv-files-using-c-sharp
    http://stackoverflow.com/questions/1375410/very-simple-c-sharp-csv-reader

    Hope it will be helpful to you.


    Regards,
    Pawan Awasthi(DNS MVM)
    +91 8123489140 (whatsApp), +60 14365 1476(Malaysia)
    pawansoftit@gmail.com

  • #768777
    There are number of ways to read CSV file, you can use OLEDB reader or EXCEL Interop application to read csv file see below snippet

    var filename = @"c:\work\test.csv";
    var connString = string.Format(
    @"Provider=Microsoft.Jet.OleDb.4.0; Data Source={0};Extended Properties=""Text;HDR=YES;FMT=Delimited""",
    Path.GetDirectoryName(filename)
    );
    using (var conn = new OleDbConnection(connString))
    {
    conn.Open();
    var query = "SELECT * FROM [" + Path.GetFileName(filename) + "]";
    using (var adapter = new OleDbDataAdapter(query, conn))
    {
    var ds = new DataSet("CSV File");
    adapter.Fill(ds);
    }
    }

    Thanks
    Koolprasd2003
    Editor, DotNetSpider MVM
    Microsoft MVP 2014 [ASP.NET/IIS]


Sign In to post your comments