Create a CSV download using silverlight 4 and C #

I am trying to find an example or code to be able to create a CSV or text file in silverlight as a download link.

I did this in ASP.net, but cannot figure out how to use Silverlight. Am I spinning my wheels? Or should I just create an ASP page? Is there any way to do this in C #?

I would like to do it right, not some hacked work, and I will be grateful for any feedback and advice.

In ASP, I would use:

Response.ContentType = "text/csv" Response.AddHeader "Content-disposition", "attachment;filename=""EPIC0B00.CSV""" Response.write.... 
+6
content-type csv silverlight download
source share
2 answers

I managed to solve a very similar code, as indicated above, simply by including the required links so that no assumptions were made, plus this is a real working example.

 using System; using System.IO; using System.Windows; using System.Windows.Controls; .... private void btnSave_Click(object sender, RoutedEventArgs e) { string data = ExportData(); // This is where the data is built SaveFileDialog sfd = new SaveFileDialog() { DefaultExt = "csv", Filter = "CSV Files (*.csv)|*.csv|All files (*.*)|*.*", FilterIndex = 1 }; if (sfd.ShowDialog() == true) { using (Stream stream = sfd.OpenFile()) { using (StreamWriter writer = new StreamWriter(stream)) { writer.Write(data); //Write the data :) writer.Close(); } stream.Close(); } } } private string ExportData() { return "!this is the exported text"; } 
+6
source share

Silverlight is a client technology. You cannot point the browser at it and "download" CSV or anything else from it.

Instead, you use the SaveFileDialog class. Here is a code snippet based on MSDN docs for it: -

 SaveFileDialog csvDialog; public Page() { InitializeComponent(); csvDialog= new SaveFileDialog(); csvDialog.Filter = "CSV Files| *.csv"; csvDialog.DefaultExt = "csv"; } private void button1_Click(object sender, RoutedEventArgs e) { bool? result = csvDialog.ShowDialog(); if (result == true) { System.IO.Stream fileStream = csvDialog.OpenFile(); System.IO.StreamWriter sw = new System.IO.StreamWriter(fileStream); // Call a method to write your CSV content to the sw here sw.Flush(); sw.Close(); } } 
+1
source share

All Articles