A colleague and I was recently looking at some old ASP.NET WebForms code which generated a potentially large CSV string and returned it in a response to a HTTP request. The original code was placed in a standard ASP.NET WebForms page in the OnLoad event handler. As the code was working with the HttpResponse object and writing the CSV directly to the HTTP output stream, we determined that this code was better placed in a HTTP Handler. The primary advantage of using a HTTP handler to generate the file is that we can bypass the unnecessary ASP.NET WebForms page life cycle.
The existing code was using a StringBuilder to generate the CSV string in the page OnLoad event handler. As you may imagine, this looked messy and was a pain to maintain. To abstract the CSV string creation logic, my colleague introduced me to a useful CSV library called LINQ to CSV. The project page link for this library is here and the library is available as a NuGet package.
The LINQ to CSV library enabled us to decorate some properties in a model class with attributes that specify how to output the property in CSV form. The example below (from the library project page) shows how to apply the attributes:
{
[CsvColumn(Name = "ProductName", FieldIndex = 1)]
public string Name { get; set; }
[CsvColumn(FieldIndex = 2, OutputFormat = "dd MMM HH:mm:ss")]
public DateTime LaunchDate { get; set; }
[CsvColumn(FieldIndex = 3, CanBeNull = false, OutputFormat = "C")]
public decimal Price { get; set; }
[CsvColumn(FieldIndex = 4)]
public string Country { get; set; }
[CsvColumn(FieldIndex = 5)]
public string Description { get; set; }
}
Once your model class is decorated, you can then use other classes of the library to generate a CSV representation of a collection containing your model instances. This representation can be output to disk as demonstrated in the code example below:
products.Add(
new Product
{
Name = "Samung Galaxy S6",
LaunchDate = DateTime.Today,
Price = 500,
Country = "United Kingdom",
Description = "This is a Samsung phone product"
}
);
products.Add(
new Product
{
Name = "Apple iPhone 5",
LaunchDate = DateTime.Today,
Price = 600,
Country = "United States",
Description = "This is an Apple phone product"
}
);
CsvFileDescription inputFileDescription = new CsvFileDescription();
inputFileDescription.SeparatorChar = ',';
inputFileDescription.FirstLineHasColumnNames = true;
CsvContext csvContext = new CsvContext();
csvContext.Write(products, @"C:\Products.csv");
Usefully, the CsvContext class of the library also supports an overload to the Write method which accepts a TextWriter stream. Passing a TextWriter stream to this overload results in the library outputing the CSV representation to your stream rather than a file on disk. In our case, we used a StreamWriter that wrote to a MemoryStream. Once the CSV file content was in the MemoryStream instance, we sent the stream contents in the HTTP response from the HTTP handler. The full HTTP handler code is below (using the example product data).
{
public bool IsReusable { get { return true; } }
public void ProcessRequest(HttpContext context)
{
context.Response.AddHeader(
"content-disposition",
"attachment;filename=BulkExport.csv"
);
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
context.Response.ContentType = "application/vnd.text";
IList<Product> products = new List<Product>();
// Add products...
var inputFileDescription = new CsvFileDescription();
inputFileDescription.SeparatorChar = ',';
inputFileDescription.FirstLineHasColumnNames = true;
using (var memoryStream = new MemoryStream())
{
using (var streamWriter = new StreamWriter(memoryStream))
{
var csvContext = new CsvContext();
csvContext.Write(products, streamWriter);
streamWriter.Flush();
context.Response.BinaryWrite(memoryStream.GetBuffer());
}
}
}
}
It was wonderfull reading your article. Great writing styleiamlinkfeeder iamlinkfeeder iamlinkfeeder iamlinkfeeder iamlinkfeeder iamlinkfeeder iamlinkfeeder iamlinkfeeder iamlinkfeeder iamlinkfeeder
ReplyDeleteIGRS Telangana portal is the all type services provide in telangana state
ReplyDeleteC# CSV Library and HTTP Handlers
ReplyDeleteVery informative post...
Top 6 Practical Reasons to Learn C# Programming Language in 2021
c# development services
A ,woman and this is what she used to remove the fat around the breast
ReplyDeleteOne of the best articles is this. I am looking for this article for a long time. At last, I found this on your website. Many many thanks for sharing your content.
ReplyDeleteBangla Calendar 2022
Cool and beautiful stylish name
Thank you ever so for you article. Really Cool.
ReplyDeletejava online training hyderabad
core java online training hyderabad
ZModeler Crack is an ideal included 3D demonstrating an interest which intends to benefit visual specialists joined by making the low. Zmodeler 3 Full Crack
ReplyDeleteEvernote Premium Crack is an extreme answer for make, make due, and sort out notes, updates, plans for the day, and substantially more in an easy! Thums Up Evernote Premium Free
ReplyDeleteMay God bless you with all of the wonderful desires of your heart and bless you to keep the many blessings that you already have.Happy Birthday My Love Quotes
ReplyDeleteWonderful blog. I happy to read your post and i have bookmarked. Keep doing...
ReplyDeleteSpousal Support in VA
Spousal Support in Virginia
Thanks for sharing such informative blog. It really helped me a lot to learn new things about Oracledbr. Keep on sharing informative and useful stuffs. Great blog!
ReplyDeleteiqra technology Salesforce administration services provide start at $2100 per month.
Are you looking for a way to watch the latest Pathan movie in high-quality and for free? Look no further! Here we provide you with the best options to Pathan Full Movie Download 4K, HD, 1080p 480p, 720p in Hindi quality for free in Hindi. We have compiled a list of reliable sources that offer the highest quality streaming and downloading services. So get ready to dive into the world of Pathan with this ultimate guide on how to download it for free !
ReplyDeleteHai! Nice blog you had , Thanks for sharing article
ReplyDeletereact js training in hyderabad
Thanks for sharing this amazing blog.r training course
ReplyDeleteMe
ReplyDeleteamazing article. r programming online course
ReplyDeleteThis is a great post. I like this topic.This site has lots of advantage.I found many interesting things from this site. It helps me in many ways.Thanks for posting.our sclinbio.com
ReplyDeletewow...! such a nice explanation and, nice article, thanks for sharing
ReplyDeletekeep posting more
The most beguiling sound I have ever heard in that framework is your voice. The most flawless spot I have ever been to is in your arms. thnx for shareing our https/-sclinbio.com
ReplyDeleteThanks for sharing such informative blog. It really helped me a lot to learn new things about Oracledbr. Keep on sharing informative and useful stuffs. Great blog!
ReplyDeleteiqra technology Salesforce administration services provide start at $2100 per month.
شركة عزل اسطح بالاحساء
ReplyDeleteشركة عزل اسطح
I’m honestly blown away by how this topic has been explained here. It’s something that usually feels pretty complicated, but the writer has done an outstanding job of making it crystal clear. I truly appreciate the effort to make it so easy for everyone to understand—kudos for such a fantastic job! Visit our link for ISO Certification in Tanzania
ReplyDeleteThank you for sharing this blog is very nice
ReplyDeleteSAP ABAP Training in Hyderabad
For example my application is Task Management, there is external Reporting application. I want communicate both ways(dual).how many ways we can architect solution. One way is consume web services.click here
ReplyDeleteyou can focus on writing code once and delivering high-quality apps to multiple platforms, all while taking full advantage of the capabilities of C# and the .NET ecosystem.click here
ReplyDelete