一、C#的应用
通过调用Response对象的WriteFile方法,可以将文本文件中的内容直接显示在浏览器上。在页面中,通过“浏览按钮”选择磁盘文件,文件路径显示在文本框中,然后单击“导入”按钮,文本文件中的所有内容将显示在Web页面上。提示:用到了FileUpLoad控件。
代码如下:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="FileTest.aspx.cs" Inherits="Ex07_Extend.FileTest" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="FileUpload1" runat="server" BorderStyle="Solid" ViewStateMode="Disabled" />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="上传" />
</div>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Ex07_Extend
{
public partial class FileTest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string fileExrensio = System.IO.Path.GetExtension(FileUpload1.FileName).ToLower();
string FileType = FileUpload1.PostedFile.ContentType;
string savepath = Server.MapPath("/~upload/");
if (!System.IO.Directory.Exists(savepath))
{
System.IO.Directory.CreateDirectory(savepath);
}
savepath = savepath + FileUpload1.FileName;
FileUpload1.SaveAs(savepath);
Response.WriteFile("D://mytext.txt");
}
}
}
}
实验结果截图