To write an array of data to a csv file from C# you can use the File.WriteAllText. This method is from System.IO namespace. The File.WriteAllText method will create and writes all the content to the file. Finally it closes the file. In most cases you just need this method to write a csv file. If the file already exists, then this method will over write the content of the file. In case if you need to append more data to the existing csv file, then you can use the File.AppendAllText method. File.AppendAllText method will open the existing file, add the string to the existing data and closes the file. Below is a sample code to write data into csv file in c# and then append more data to it.
Sample code to write data into csv file in c#
string strFilePath = @"C:\testfile.csv"; string strSeperator = ","; StringBuilder sbOutput = new StringBuilder(); int[][] inaOutput = new int[][]{ new int[]{1000, 2000, 3000, 4000, 5000}, new int[]{6000, 7000, 8000, 9000, 10000}, new int[]{11000, 12000, 13000, 14000, 15000} }; int ilength = inaOutput.GetLength(0); for (int i = 0; i < ilength; i++) sbOutput.AppendLine(string.Join(strSeperator, inaOutput[i])); // Create and write the csv file File.WriteAllText(strFilePath, sbOutput.ToString()); // To append more lines to the csv file File.AppendAllText(strFilePath, sbOutput.ToString());
Created File
Related
- Read the the article on comparison between ViewMode, ViewData, ViewBag and TempData.
Reference
- Similar question and answer in stack overflow.