This code reads a CSV file named “data.csv” in C# and converts it into a DataTable. Then it uses the JsonConvert.SerializeObject() method from Newtonsoft.Json library from NuGet packages to convert the DataTable to a JSON string. The JSON string is then written to a file named “data.json” using the File.WriteAllText() method.

using System;
using System.IO;
using System.Linq;
using System.Data;
using Newtonsoft.Json;

class Program
    static void Main()
        // Read the CSV file into a DataTable
        DataTable table = CsvToDataTable("data.csv");

        // Convert the DataTable to a JSON string
        string json = JsonConvert.SerializeObject(table, Formatting.Indented);

        // Write the JSON string to a file
        File.WriteAllText("data.json", json);

    static DataTable CsvToDataTable(string filePath)
        DataTable table = new DataTable();

        // Read the CSV file into a string array
        string[] csvData = File.ReadAllLines(filePath);

        // Get the column names
        string[] columnNames = csvData[0].Split(',');
        foreach (string columnName in columnNames)

        // Add the data rows
        for (int i = 1; i < csvData.Length; i++)
            string[] data = csvData[i].Split(',');

        return table;

Line by Line Explanation of Code:

  • The using statements at the top of the file import the necessary namespaces for working with data tables, files, and JSON serialization.
  • The Main() method is called when the program starts.
  • The CsvToDataTable() method is called with the file path “data.csv” as an argument and returns a DataTable with the data from the CSV file.
  • The DataTable is converted to a JSON string using the JsonConvert.SerializeObject() method.
  • The JSON string is written to a file named “data.json” using the File.WriteAllText() method.
  • The CsvToDataTable method starts by initializing a new DataTable.
  • It reads all lines of the CSV file into a string array called csvData.
  • It splits the first element of the array, which contains the column names, by the comma separator to get the column names.
  • It adds the column names to the DataTable.
  • It loops through the remaining elements of the array, which contain the data rows, and splits each element by the comma separator to get the data fields.
  • It adds the data fields as a new row to the DataTable.
  • Finally, it returns the DataTable.
  • This code allows you to convert the data from a CSV file to a JSON file in C# and you can use this JSON in various ways like sending it to the server, or using it for some other purpose.

Similar Posts