动态生成文本文件并在新的浏览器窗口中显示

时间:2015-04-18 14:22:54

标签: c# asp.net

我已经创建了文本文件并添加了内容。

在此之后,我想在Web浏览器中显示上面生成的文本文件,并将文件保存为.txt格式。

FileStream fs = new FileStream("D:\\overflow.txt", FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter writer = new StreamWriter(fs);
writer.Write("Hello Welcome");
writer.Close();

1 个答案:

答案 0 :(得分:1)

以下示例代码适用于ASPX.Net app:

<%@ Page Language="C#" %>
<%@ Import Namespace="System.IO" %>

<!DOCTYPE html>

<script runat="server">

    protected void Button1_Click(object sender, EventArgs e)
    {
        // get a temporary file name so we don't conflict with concurrent user
        string fileName = Path.GetRandomFileName();
        fileName = Path.ChangeExtension(fileName, "txt");

        // Now map the file to a path within the host directory
        string outputFileName = MapPath(fileName);

        // write some data to the file
        FileStream fs = new FileStream(outputFileName, FileMode.OpenOrCreate, FileAccess.Write);
        StreamWriter writer = new StreamWriter(fs);

        writer.WriteLine("Hello Welcome");
        writer.WriteLine("Input Box: " + this.TextBox1.Text);
        writer.WriteLine(string.Empty);
        writer.WriteLine(DateTime.Now.ToLongTimeString());
        writer.Close();

        // now open the url in another browser tab
        Page.ClientScript.RegisterStartupScript(this.GetType(), "windowKey", "window.open('" + fileName + "');", true);
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Create Temp File</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <p>Generate a temporary text file and display in browser</p>
        <br />
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
    </div>
    </form>
</body>
</html>

带按钮的网页:

sample code running

显示文字文件的网页:

Sample code displaying text file