Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a CSV download using silverlight 4 and c#

I'm struggling to find an example or code to be able to create CSV or text file in silverlight as a downloadable link.

I've done this in ASP.net but can't figure out a way using Silverlight. Am I spinning my wheels? Or should I just create an ASP page? Is there a way of doing this in c#?

I'd like to do this the right way and not some hack job and will appreciate any feedback and advice.

In ASP I would of used:

Response.ContentType = "text/csv"
Response.AddHeader "Content-disposition", "attachment;filename=""EPIC0B00.CSV"""
Response.write....
like image 479
Rick Avatar asked Feb 18 '11 02:02

Rick


1 Answers

I was able to solve with very similar code as above, just including required references so there is no assumptions made, plus this is an actual 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";
    }
like image 160
Rick Avatar answered Sep 19 '22 12:09

Rick