How to save data to CSV file in C# application

Saving data to a file can be a very powerful technique when it comes to data analysis or reporting. If you are creating a C# application, you can create a CSV file to save your data into.

Saving data to a file can be a very powerful technique when it comes to data analysis or reporting. If you are creating a C# application, you can create a CSV file to save your data into.

CSV files are text files where you can store values. You can separate each data point by adding a comma between the values. This allows you to organize your data in rows and columns. You can then visualize these rows and columns when you open the file in Microsoft Excel.

How do you store data in a CSV file?

A CSV file is a text file where you can separate data points and values ​​with commas.

When storing data in a file using a program, add each row as a separate line. To create a column, format the data by adding a comma to separate each value or data point.

StringBuilder output = new StringBuilder(); output.AppendLine(string.Join(",", new String[] { "1", "2", "3" })); // CSV File Output = 1,2,3

How to create Console Application and Test Data

Create a C# console application using Visual Studio and add some test data to the program.

1. Open Visual Studio and click Create a new project .

How to save data to CSV file in C# application Picture 1How to save data to CSV file in C# application Picture 1

2. Click Console Application and then click Next.

How to save data to CSV file in C# application Picture 2How to save data to CSV file in C# application Picture 2

3. Name the project and store it in a location of your choice. Click Next.

How to save data to CSV file in C# application Picture 3How to save data to CSV file in C# application Picture 3

4. Leave the default Target Framework as is and click Create. This causes Visual Studio to create a default C# "Hello World" console application.

5. At the top of the program, enter System.IO and System.Text. This will allow you to store data in CSV files and also help format strings for CSV format.

using System.IO; using System.Text;

6. Add some test data to the program. Below the Main Program class , create a new class named Student. Use the Student class to store information about students, such as student ID, first name, last name, and date of birth. If you are not familiar with how classes work, you can learn more about Classes in C#.

 

public class Student { public int StudentId; public string FirstName; public string LastName; public string Dob; public Student(int StudentId, string FirstName, string LastName, string Dob) { this.StudentId = StudentId; this.FirstName = FirstName; this.LastName = LastName; this.Dob = Dob; } }

7. Inside the Main() function , delete the existing "Hello World" code. Replace it with a new students array:

static void Main(string[] args) { // Create an array with a list of students Student[] students = { new Student(1, "John", "Smith", "03/04/1990"), new Student(2, "Adam", "Van Houten", "07/07/1991"), new Student(3, "Joey", "Richardson", "01/02/1992"), new Student(4, "Matt", "Adams", "05/05/1992"), new Student(5, "Jake", "Smith", "04/04/1994"), }; }

How to create a new CSV file and add headings

Use the file path to create a new CSV file and add headings to the file.

1. Inside the Main() function , under the student list, create a new CSV file. Use the file path to determine where you want to save the file. If the file does not exist, the program will automatically create a new CSV file at that location.

String file = @"C:UsersSharlDesktopOutput.csv";

2. Use StringBuilder to create a new formatted string. Using a separator variable to store commas will separate each value for each column.

String separator = ","; StringBuilder output = new StringBuilder();

3. Create headings for the top row of the CSV file. Add headings for the student's StudentID, first name, last name, and date of birth.

String[] headings = { "StudentID", "First Name", "Last Name", "Date Of Birth" }; output.AppendLine(string.Join(separator, headings));

How to store values ​​in CSV file

For each student in the students array, create a new row to store their details inside the CSV file.

1. Add a for loop for each student. Each student will display their detailed information (including student ID, last name, first name and date of birth) in a different row of the CSV file.

foreach (Student student in students) { }

2. Inside the for loop, create a list of student attributes. Use StringBuilder to format the string and add commas between each value.

String[] newLine = { student.StudentId.ToString(), student.FirstName, student.LastName, student.Dob }; output.AppendLine(string.Join(separator, newLine));

3. Alternatively, you can format rows using string.Format , instead of StringBuilder.

string newLine = string.Format("{0}, {1}, {2}, {3}", student.StudentId.ToString(), student.FirstName, student.LastName, student.Dob); output.AppendLine(string.Join(separator, newLine));

4. After the for loop, write all the data to the file. Add a try-catch block to detect any potential problems that may occur when writing data to the file. This will ensure the program does not crash if it cannot save the file successfully.

try { File.AppendAllText(file, output.ToString()); } catch(Exception ex) { Console.WriteLine("Data could not be written to the CSV file."); return; }

5. Notify the user that the program was able to create the file successfully.

Console.WriteLine("The data has been successfully saved to the CSV file");

How to view data in file

1. Run the program and navigate to the location of the created CSV file to open it.

How to save data to CSV file in C# application Picture 4How to save data to CSV file in C# application Picture 4

2. Wait for the console application to compile and display a success message.

How to save data to CSV file in C# application Picture 5How to save data to CSV file in C# application Picture 5

3. Navigate to the location where you stored your file and open the newly created Output.csv file. Open the file with Microsoft Excel to view data in rows and columns.

How to save data to CSV file in C# application Picture 6How to save data to CSV file in C# application Picture 6

4. Open the CSV file with any text editor, such as Notepad++, to view the formatted data separated by commas.

How to save data to CSV file in C# application Picture 7How to save data to CSV file in C# application Picture 7

You can save data in your C# application by writing it to a CSV file. Depending on the data, you can add each object or data set as a separate row. Use commas to separate each data point or value into columns.

You can view the raw CSV data in a text editor to see your formatted data points. You can also view your CSV file to see rows and columns visually using Microsoft Excel.

4.5 ★ | 2 Vote