Home > Backend Development > C++ > How Can I Efficiently Load CSV Data into a .NET DataTable?

How Can I Efficiently Load CSV Data into a .NET DataTable?

Susan Sarandon
Release: 2025-01-27 19:21:14
Original
582 people have browsed it

How Can I Efficiently Load CSV Data into a .NET DataTable?

Importing CSV Data into a .NET DataTable: A Practical Guide

Efficiently handling CSV data is crucial for many .NET applications. This article demonstrates how to seamlessly import CSV files into a .NET DataTable, a powerful ADO.NET structure for managing tabular data.

Leveraging the OleDb Provider

While standard ADO.NET lacks direct CSV import functionality, the OleDb provider provides a robust solution. A common challenge, however, involves the correct interpretation of numeric data. We'll address this using a schema.ini file (explained below).

A Reusable C# Method

The following C# function reads a CSV file and populates a DataTable, handling header rows appropriately:

public static DataTable LoadCsvToDataTable(string filePath, bool hasHeaderRow)
{
    string directory = Path.GetDirectoryName(filePath);
    string filename = Path.GetFileName(filePath);
    string header = hasHeaderRow ? "Yes" : "No";
    string sqlQuery = $"SELECT * FROM [{filename}]";

    using (OleDbConnection connection = new OleDbConnection(
        $"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={directory};Extended Properties=\"Text;HDR={header}\""))
    using (OleDbCommand command = new OleDbCommand(sqlQuery, connection))
    using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
    {
        DataTable dataTable = new DataTable();
        dataTable.Locale = CultureInfo.CurrentCulture; // Ensures correct data type handling
        adapter.Fill(dataTable);
        return dataTable;
    }
}
Copy after login

This method uses the current culture to ensure accurate data type interpretation, preventing common issues with numeric values. This approach avoids the need for manual type conversions.

The above is the detailed content of How Can I Efficiently Load CSV Data into a .NET DataTable?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template