Neeraj Kumar Neeraj Kumar - 2 months ago 12
C# Question

How do I Create a CSV file in C#

I am new to file system. I need to create a simple csv file and need to write string in the file and read it back.

I am getting some unicode value in the file that got created. How do i write string value by creating csv and reading back from it.

So far I have wrote this. Need little hele here.

Below is my code.

static void Main()
{
string folderName = @"D:\Data";
string pathString = System.IO.Path.Combine(folderName, "SubFolder");
System.IO.Directory.CreateDirectory(pathString);
string fileName = System.IO.Path.GetRandomFileName();
pathString = System.IO.Path.Combine(pathString, fileName);
Console.WriteLine("Path to my file: {0}\n", pathString);

if (!System.IO.File.Exists(pathString))
{
using (System.IO.FileStream fs = System.IO.File.Create(pathString))
{
{
byte a = 1;
fs.WriteByte(a);
}
}
}

// Read and display the data from your file.
try
{
byte[] readBuffer = System.IO.File.ReadAllBytes(pathString);
foreach (byte b in readBuffer)
{
Console.Write(b + " ");
}
Console.WriteLine();
}
catch (System.IO.IOException e)
{
Console.WriteLine(e.Message);
}
}

Answer

You can write a csv file using streamwriter. Your file will be located in bin/Debug (if running debug mode and not stating otherwise).

 var filepath = "your_path.csv";
 using (StreamWriter writer = new StreamWriter(new FileStream(filepath,
 FileMode.Create, FileAccess.Write)))
 {
     writer.WriteLine("sep=,");
     writer.WriteLine("Hello, Goodbye");
 }