CSV files are text files that you can store values in. You can separate each data point by adding commas between 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 make the columns, format the data by adding a comma to separate each value or data point.
How to Create the Console Application and Test Data
Create a C# console application using Visual Studio, and add some test data to the program.
Open Visual Studio and click on Create a new project. Click on Console Application and click Next. Name your project and store it in a location of your choice. Click on Next. Leave the default Target Framework and click on Create. This causes Visual Studio to generate a default “Hello World” C# console application. At the top of the program, import System. IO and System. Text. This will allow you to store data in the CSV file, and also help format the string for CSV format. using System. IO;using System. Text; Add some Test Data to the Program. Underneath the Main Program class, create a new Class called Student. Use the Student class to store information about students, such as their student ID, first name, last name, and date of birth. If you are unfamiliar 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; }} Inside the Main() function, remove the existing “Hello World” code. Replace it with a new array of students: 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’s path to create the new CSV file, and add the headings to the file.
Inside the Main() function, underneath the list of students, create a new CSV file. Use a file path to determine where you want to store the file. If the file does not exist, the program will automatically create a new CSV file at that location. String file = @“C:\Users\Sharl\Desktop\Output. csv”; Use the StringBuilder to create a new formatted string. Use the separator variable to store the comma that will separate each value for each column. String separator = “,";StringBuilder output = new StringBuilder(); Create the headings for the top row of the CSV file. Add the 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 the CSV File
For each student in the students array, create a new row to store their details inside the CSV file.
Add a for loop for each student. Each student will show their details (including their studentID, first name, last name, and date of birth) in a different row of the CSV file. foreach (Student student in students){} Inside the for loop, create a list of the student’s attributes. Use the StringBuilder to format the string to add a comma between each value. String[] newLine = { student. StudentId. ToString(), student. FirstName, student. LastName, student. Dob };output. AppendLine(string. Join(separator, newLine)); Alternatively, you can format the row using string. Format, instead of the StringBuilder. string newLine = string. Format("{0}, {1}, {2}, {3}”, student. StudentId. ToString(), student. FirstName, student. LastName, student. Dob);output. AppendLine(string. Join(separator, newLine)); After the for loop, write all the data to the file. Add a try-catch block to catch any potential problems that could happen when writing the data to the file. This will ensure the program does not crash if the program is unable to 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;} Inform the user that the program was able to successfully create the file. Console. WriteLine(“The data has been successfully saved to the CSV file”);
How to View the Data in the File
Run the program and navigate to the location of the created CSV file to open it.
Click on the green play button at the top of the Visual Studio window. Wait for the console application to compile and display the success message. Navigate to the location where you stored your file, and open the newly created Output. csv file. Open the file using Microsoft Excel to view the data as rows and columns. Open the CSV file using any text editor, such as Notepad++, to view the formatted data separated by commas.
Storing Data in CSV Files Using C#
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 set of data as a separate row. Use commas to separate each data point or value into columns.
You can view a raw CSV in a text editor to see your formatted data points. You can also view your CSV file to visually see rows and columns using Microsoft Excel.
There are many other ways you can write data to CSV files. You can also explore how to write data to CSV files using Node.js.