【问题标题】:Create a CSV download using silverlight 4 and c#使用 silverlight 4 和 c# 创建 CSV 下载
【发布时间】:2011-06-29 13:14:21
【问题描述】:

我正在努力寻找能够在 silverlight 中创建 CSV 或文本文件作为可下载链接的示例或代码。

我已经在 ASP.net 中完成了这项工作,但无法找到使用 Silverlight 的方法。我在旋转我的轮子吗?或者我应该只创建一个 ASP 页面?有没有办法在 c# 中做到这一点?

我希望以正确的方式来做这件事,而不是做一些黑客工作,并且会感谢任何反馈和建议。

在 ASP 中我会使用:

Response.ContentType = "text/csv"
Response.AddHeader "Content-disposition", "attachment;filename=""EPIC0B00.CSV"""
Response.write....

【问题讨论】:

  • 在这种情况下,我使用 ashx 处理程序和来自 silverlight 应用程序的链接。

标签: silverlight csv download content-type


【解决方案1】:

我能够使用与上面非常相似的代码来解决问题,只包括所需的引用,因此没有做出任何假设,而且这是一个实际的工作示例。

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";
    }

【讨论】:

    【解决方案2】:

    Silverlight 是一种客户端技术。您不能将浏览器指向它并从中“下载”CSV 或其他任何内容。

    改为使用SaveFileDialog 类。这是一段基于 MSDN 文档的代码:-

    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();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-17
      • 1970-01-01
      • 2012-07-22
      • 1970-01-01
      • 2018-11-08
      • 2013-02-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多