I am creating a CSV file and I am using StringBuilder at the moment I come to a new Class “CommaDelimitedStringCollection“.
Can anyone tell me which is betterto use to write the file data. also what do you think of using TextWriter.
Thanks
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
If writing a CSV were a very complex task, I might rely on helpers like
CommaDelimitedStringCollection. However, it isn’t complicated, so there’s no reason to introduce an extra helper class in here along with the associated perf hit.If I needed to build a string in memory for some reason, such as implementing a general
ToString()method, I would useStringBuilderinstead of straight concatenation. However, in this case you are writing to a stream of some kind, so you don’t need this extra step either.TextWriteris an abstract class, but you want the hierarchy of classes therein, specificallyStreamWriter. This class has a number of constructor overloads; one takes a file name, if you want to write to a local file, and another takes aStreamobject, if you want to write directly to a stream (for exampleResponse.OutputStreamin ASP.NET).I actually did a quick Google search and there don’t appear to be any good examples of actually implementing a CSV download, if that’s what you’re trying to do, so here is one:
This uses the most common escaping mechanism for CSV – quotes around strings, another quote as an escape character.
If you just want to export to a local file instead, get rid of all the
Responselines inExportCsvAttachmentand use theStreamWriterconstructor that takes a path.