C# 如何生成txt文件,然后在ASP.NET Web表单中强制下载?

C# 如何生成txt文件,然后在ASP.NET Web表单中强制下载?,c#,asp.net,C#,Asp.net,我需要将处理程序设置为元素。当用户单击时,txt文件必须以代码隐藏方式生成,并且必须由用户自动下载。不需要从用户那里获取任何数据。所有文件内容都将在代码隐藏中生成。例如,如何将包含此变量内容的txt文件返回给用户: string s = "Some text.\nSecond line."; 您只需在服务器端生成文件,然后将其向下推给用户即可s将是您将生成的文件的内容 创建文件 创建新文件非常简单,只需将数据写入其中 // var s that you're having File.Creat

我需要将处理程序设置为
元素。当用户单击时,txt文件必须以代码隐藏方式生成,并且必须由用户自动下载。不需要从用户那里获取任何数据。所有文件内容都将在代码隐藏中生成。例如,如何将包含此变量内容的txt文件返回给用户:

string s = "Some text.\nSecond line.";

您只需在服务器端生成文件,然后将其向下推给用户即可
s
将是您将生成的文件的内容

创建文件 创建新文件非常简单,只需将数据写入其中

// var s that you're having
File.Create(Server.MapPath("~/NewFile.txt")).Close();
File.WriteAllText(Server.MapPath("~/NewFile.txt"), s);
这将创建一个新文件(如果不存在)并将变量s的内容写入其中

将其向下推给用户 您可以允许用户使用以下代码下载它

// Get the file path
var file = Server.MapPath("~/NewFile.txt");
// Append headers
Response.AppendHeader("content-disposition", "attachment; filename=NewFile.txt");
// Open/Save dialog
Response.ContentType = "application/octet-stream";
// Push it!
Response.TransmitFile(file);

这将使他拥有您刚刚创建的文件。

对于这种工作,您应该动态创建文件。 请参阅代码:

    protected void Button_Click(object sender, EventArgs e)
    {
        string s = "Some text.\r\nSecond line.";

        Response.Clear();
        Response.AddHeader("content-disposition", "attachment; filename=testfile.txt");
        Response.AddHeader("content-type", "text/plain");

        using (StreamWriter writer = new StreamWriter(Response.OutputStream))
        {
            writer.WriteLine(s);
        }
        Response.End();
    }
}

请注意,对于新行,您需要使用\r\n,而不是仅使用\n或对每行使用WriteLine函数

我有一个类似的用例,但用例稍微复杂一点

我确实生成了不同类型的文件。我编写了一个容器类附件,它将生成的文件的内容类型和值保存为Base64字符串

public class Attachment {
   public string Name {get;set;}
   public string ContentType {get;set;}
   public string Base64 {get;set;}
}
这使我能够使用相同的下载方法为不同的文件类型提供服务

protected void DownloadDocumentButton_OnClick(object sender, EventArgs e) {
  ASPxButton button = (ASPxButton) sender;
  int attachmentId = Convert.ToInt32(button.CommandArgument);

  var attachment = mAttachmentService.GenerateAttachment(attachmentId);

  Response.Clear();
  Response.AddHeader("content-disposition", $"attachment; filename={attachment.Name}");
  Response.AddHeader("content-type", attachment.ContentType);
  Response.BinaryWrite(Convert.FromBase64String(attachment.Base64));
  Response.End();
}

使用磁盘并不是一种明智的方法,它可以在内存中完成,因为磁盘IO会引入延迟和对多线程的关注(这在ASP.net应用程序中很可能是问题)。我喜欢这个想法,但由于某些原因它不起作用。我可以在调试器中看到已创建响应,但结果中并没有下载任何文件。顺便说一句,这里是一个按钮标记。这里可能有问题:
这是一种非常常见的方法,必须正确。我想可能是某种浏览器设置导致了这个问题。您可以尝试使用其他浏览器吗?或者它可能被您的防病毒软件阻止。我禁用了防病毒软件并更改了浏览器。结果是一样的。它可以与回发或类似的东西连接吗?您可以用Response.ContentType=“text/plain”替换第二个addheader函数吗;