I need to provide a csv file generated by the server for download by url. The problem is the resulting csv file loses newline symbols. All the data appears on one row (single line), and that is not what I need. Original file is fine, has all lines correctly. a I’m on .Net Framework 4.7.1.
Here’s example code:
public async Task<FileResult> Download()
{
string filepath = AppDomain.CurrentDomain.BaseDirectory + $"filename.csv";
if (!System.IO.File.Exists(filepath))
System.IO.File.WriteAllText(filepath, "");
return File(filepath, "text/csv", $"filename.csv");
}
I have tried multiple things, providing filestream, byte array, but all of that results in the same thing. How can I fix that?
2
Answers
This is how I create my CSV content:
P.S.: Please note that this not the whole code but just part of it. It needs some collection or some array to iterate on it to create lines.
You need to use AppendLine at the end of each row when creating the CSV content.
Edit to original answer:
This is how i return my file. Maybe this helps
By the way, I am not creating file in the file system just returning it as a file response to the user.
The issue you’re experiencing with newline symbols in your CSV file might be related to how line endings are handled in different environments (e.g., Windows, Unix). To ensure that the downloaded CSV file retains proper line endings, you can specify the encoding when writing the file. You should use the
StreamWriter
class and specify the encoding as follows:By using
StreamWriter
with the UTF-8 encoding (or the encoding that matches your requirements), you should ensure that the line endings are correctly handled, and your downloaded CSV file will have the expected line breaks.