相当于响应。在 Windows 申请中

Equivalent of Response. in Windows Application

我正在尝试将文本数据传输到文本文件并使其可下载。在 Web 应用程序中使用 Response 很容易。但是当通过 windows 传输相同的东西时,我无法获得解决方案,我们可以通过将数据写入文本文件来解决,但是如何使该文件可下载?

这是我写的网页格式代码

    private void ButtonSaveText_Click(object sender, EventArgs e)
    {
        //Build the Text file data.
        string TextFileData = string.Empty;
        TextFileData = TextFileData + "PAY SLIP FOR THE MONTH --------------" + Environment.NewLine + Environment.NewLine + Environment.NewLine;
        for (int i = 0; i < GridViewPaySlip.Rows.Count; i++)
        {
            for (int j = 0; j < GridViewPaySlip.HeaderRow.Cells.Count; j++)
            {
                TextFileData += GridViewPaySlip.HeaderRow.Cells[j].Text + "\t\t\t" + GridViewPaySlip.Rows[i].Cells[j].Text + Environment.NewLine + Environment.NewLine + Environment.NewLine;
            }
        }

        //Download the Text file.
        Response.Clear();
        Response.Buffer = true;
        string FileName = String.Format("{0}__{1}{2}", "payslip", EmployeeIdTemp, ".txt");
        Response.AddHeader("content-disposition", "attachment;filename=" + FileName);
        Response.Charset = "";
        Response.ContentType = "application/text";
        Response.Output.Write(TextFileData);
        Response.Flush();
        Response.End();
    }

我认为这里对表单应用程序和网站之间的区别以及网络服务器的作用存在一些误解。

在创建文本文件方面,真的很简单:

using (System.IO.StreamWriter file = new System.IO.StreamWriter("C:\example.txt"))
{
    file.WriteLine(TextFileData);
}

就是这样。还有其他方法,该示例不处理编码或任何内容,但它保存了文件。

就 "making it downloadable" 而言,这与应用程序没有任何关系。相反,您需要确保将文本文件保存到您的网络服务器正在提供服务的文件夹中(并且该网络服务器支持该文件类型)。

new StreamWriter("D:\Websites\Payslips\payslip_" + EmployeeIdTemp + ".txt"))

或者您可能使用的任何路径。

希望对您有所帮助!

正如"Octopoid"所述,您有点困惑。

想一想。您不会 "download" 在桌面应用程序中。在 Web 应用程序中,有必要将文件从服务器下载到客户端。

在桌面应用中,没有服务器也没有客户端,所以"download"的概念不存在。

您可能正在考虑这样一个事实,即网络应用程序中的下载可能涉及一些允许将下载的文件保存在用户选择的位置的对话框。这就是 SaveFileDialog class 允许你做的。示例:

if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
    using (var stream = saveFileDialog1.OpenFile())
    {
        // code to write to the stream
    }
}