How to Convert CSV to String in C#?
CSV (Comma-Separated Values) files are a popular data format for storing tabular data, and working with them in C# can be a common requirement in various applications. We will use the StreamReader
class to read the contents of a CSV file and then store them as strings.
using System;
using System.IO;
class Program
{
static void Main()
{
// Specify the path to your CSV file
string filePath = "rolesdoc.csv";
try
{
// Read the CSV file
using (StreamReader reader = new StreamReader(filePath))
{
// Convert CSV content to a string
string csvString = reader.ReadToEnd();
// Display the converted string
Console.WriteLine("CSV to String Conversion Output:");
Console.WriteLine(csvString);
}
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
}
Output:
Assuming we have a sample CSV file named "rolesdoc.csv" with the following content:
Name, Age, Occupation
Smith Peter, 30, Developer
Arum Kumar, 25, Designer
Jagan Prabhu, 35, Manager
The program output will be:
CSV to String Conversion Output:
Name, Age, Occupation
Smith Peter, 30, Developer
Arum Kumar, 25, Designer
Jagan Prabhu, 35, Manager
The program reads the CSV file using a StreamReader
and then uses the ReadToEnd()
method to convert the file content into a single string. The converted string is then displayed on the console.
Comments (0)