Writing data into CSV file in C#
UPDATE
Back in my naïve days, I suggested doing this manually (it was a simple solution to a simple question), however due to this becoming more and more popular, I'd recommend using the library CsvHelper that does all the safety checks, etc.
CSV is way more complicated than what the question/answer suggests.
Original Answer
As you already have a loop, consider doing it like this:
//before your loop
var csv = new StringBuilder();
//in your loop
var first = reader[0].ToString();
var second = image.ToString();
//Suggestion made by KyleMit
var newLine = string.Format("{0},{1}", first, second);
csv.AppendLine(newLine);
//after your loop
File.WriteAllText(filePath, csv.ToString());
Or something to this effect.
My reasoning is: you won't be need to write to the file for every item, you will only be opening the stream once and then writing to it.
You can replace
File.WriteAllText(filePath, csv.ToString());
with
File.AppendAllText(filePath, csv.ToString());
if you want to keep previous versions of csv in the same file
C# 6
If you are using c# 6.0 then you can do the following
var newLine = $"{first},{second}"
EDIT
Here is a link to a question that explains what Environment.NewLine
does.
How do I Create a CSV file in C#
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");
}
Writing a CSV file in .net
If there are any commas in your cell, surround the entire cell with double quotes, eg:
cell 1,cell 2,"This is one cell, even with a comma",cell4,etc
And if you want a literal double quote, do two of them, eg:
cell 1,cell 2,"This is my cell and it has ""quotes"" in it",cell 4,etc
As for dates, stick to ISO format, and you should be fine (eg yyyy-mm-dd hh:mm:ss)
Writing in an CSV file using C#
CSV is absolutely NOT a SIMPLE file format, it is a sufficiently elaborate format that is able to encompass almost any kind of data regardless of shape or size.
The CSV format is capable of dealing with optional parameters vs non optional, data with or without line breaks, and should be able to work with or without field escaping characters in any field without line breaks and is required to have field escaping characters in fields with line breaks.
You should not ever work with CSV files by hand, you should utilize FileHelpers to work with CSV files.
At this point I no longer use FileHelpers as my goto CSV parsing library I use CsvHelper from Josh Close.
Create a .csv file in C#
This the approach i normally take. Probably not the most efficient though.
/// <summary>
/// Generates the contents of the log file.
/// </summary>
/// <returns>The contents of the log file.</returns>
internal string GenerateLogFile()
{
StringBuilder csvExport = new StringBuilder();
csvExport.AppendLine(Resources.CSVHeader);
foreach (DataRow row in this.logEntries.Rows)
{
csvExport.AppendLine(
string.Format(
"\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}\",\"{5}\",\"{6}\",\"{7}\",\"{8}\", \"{9}\"",
row[ColumnNames.LogTime], row[ColumnNames.Field1], row[ColumnNames.Field2], row[ColumnNames.Field3], row[ColumnNames.Field4], row[ColumnNames.Field5], row[ColumnNames.Field6], row[ColumnNames.Field7], row[ColumnNames.Field8], row[ColumnNames.Field9]));
}
return csvExport.ToString();
}
/// <summary>
/// Adds the CSV file to the response.
/// </summary>
/// <param name="csvExportContents">The contents of the CSV file.</param>
internal void DisplayLogFile(string csvExportContents)
{
byte[] data = new ASCIIEncoding().GetBytes(csvExportContents);
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "APPLICATION/OCTET-STREAM";
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=Export.csv");
HttpContext.Current.Response.OutputStream.Write(data, 0, data.Length);
HttpContext.Current.Response.End();
}
Write to CSV file and export it?
Rom, you're doing it wrong. You don't want to write files to disk so that IIS can serve them up. That adds security implications as well as increases complexity. All you really need to do is save the CSV directly to the response stream.
Here's the scenario: User wishes to download csv. User submits a form with details about the csv they want. You prepare the csv, then provide the user a URL to an aspx page which can be used to construct the csv file and write it to the response stream. The user clicks the link. The aspx page is blank; in the page codebehind you simply write the csv to the response stream and end it.
You can add the following to the (I believe this is correct) Load event:
string attachment = "attachment; filename=MyCsvLol.csv";
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.AddHeader("content-disposition", attachment);
HttpContext.Current.Response.ContentType = "text/csv";
HttpContext.Current.Response.AddHeader("Pragma", "public");
var sb = new StringBuilder();
foreach(var line in DataToExportToCSV)
sb.AppendLine(TransformDataLineIntoCsv(line));
HttpContext.Current.Response.Write(sb.ToString());
writing to the response stream code ganked from here.
How to create multiple CSV file in ASP .Net
I am not sure what do you mean about follow problem.
#but not writing another CSV file#
in your code, obviously, you wrote same file in the loop; why do not you change it to
string fileName = "myfile"+listItem.Value+".csv";//change filename?
string filePath = Server.MapPath("~/file" + fileName);
using (StreamWriter sw = new StreamWriter(filePath, false))
{
sw.Write(csv);
}
Related Topics
Is Bcrypt a Good Hashing Algorithm to Use in C#? How to Find It
Why Is Typedreference Behind the Scenes? It's So Fast and Safe... Almost Magical!
How to Get the Line Number Which Threw Exception
Why Are Subjects Not Recommended in .Net Reactive Extensions
Performing Inserts and Updates with Dapper
Can You Configure Log4Net in Code Instead of Using a Config File
Display a Image in a Console Application
How to Change Time in Datetime
C# Pattern to Prevent an Event Handler Hooked Twice
Convert Word Doc and Docx Format to PDF in .Net Core Without Microsoft.Office.Interop
Wpf Mvvm Why Use Contentcontrol + Datatemplate Views Rather Than Straight Xaml Window Views
Explicitly Cast Generic Type Parameters to Any Interface
Convert Datetime for MySQL Using C#
How to Capture the Mouse Move Event