none
How to create a .CSV file in C# ?

    Question


  • Hi

    I have a 2 dimensional array as my final output from the application (designed in c#) now I need to create .CSV file to store this value, Could anyone tell me how do I do this in C# ?

    Reply awaited.

    Thanks.




    SID
    Wednesday, July 09, 2008 3:40 AM

Answers

  • I hope this can get you started...

    1             string filePath = @"C:\test.csv";  
    2             string delimiter = ",";  
    3  
    4             string[][] output = new string[][]{  
    5                 new string[]{"Col 1 Row 1""Col 2 Row 1""Col 3 Row 1"},  
    6                 new string[]{"Col1 Row 2""Col2 Row 2""Col3 Row 2"}  
    7             };  
    8             int length = output.GetLength(0);  
    9             StringBuilder sb = new StringBuilder();  
    10             for (int index = 0; index < length; index++)  
    11                 sb.AppendLine(string.Join(delimiter, output[index]));  
    12  
    13             File.WriteAllText(filePath, sb.ToString()); 
    • Marked as answer by Sid0404 Wednesday, July 09, 2008 6:39 AM
    • Marked as answer by Sid0404 Wednesday, July 09, 2008 6:39 AM
    • Marked as answer by Sid0404 Wednesday, July 09, 2008 6:40 AM
    • Marked as answer by Sid0404 Wednesday, July 09, 2008 6:40 AM
    Wednesday, July 09, 2008 4:46 AM

All replies

  • I hope this can get you started...

    1             string filePath = @"C:\test.csv";  
    2             string delimiter = ",";  
    3  
    4             string[][] output = new string[][]{  
    5                 new string[]{"Col 1 Row 1""Col 2 Row 1""Col 3 Row 1"},  
    6                 new string[]{"Col1 Row 2""Col2 Row 2""Col3 Row 2"}  
    7             };  
    8             int length = output.GetLength(0);  
    9             StringBuilder sb = new StringBuilder();  
    10             for (int index = 0; index < length; index++)  
    11                 sb.AppendLine(string.Join(delimiter, output[index]));  
    12  
    13             File.WriteAllText(filePath, sb.ToString()); 
    • Marked as answer by Sid0404 Wednesday, July 09, 2008 6:39 AM
    • Marked as answer by Sid0404 Wednesday, July 09, 2008 6:39 AM
    • Marked as answer by Sid0404 Wednesday, July 09, 2008 6:40 AM
    • Marked as answer by Sid0404 Wednesday, July 09, 2008 6:40 AM
    Wednesday, July 09, 2008 4:46 AM

  • Thanks, a lot. Just got the output as .csv

    SID
    Wednesday, July 09, 2008 6:39 AM
  • Dennis,

    While your code is very helpful, do you know of of any samples available for reading and writing(especially) to CSV files?

    thank you,
    Neil
    neil
    Sunday, June 28, 2009 10:52 PM
  • Tuesday, December 28, 2010 9:26 PM
  • I downloaded the test project CsvFileTest, my Visual Studio 2010 cant open the project. Which version do you use? thks
    Thursday, June 27, 2013 1:33 PM