cs代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
public partial class 文件读取 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string[] arrs = Directory.GetFiles(MapPath("files"), "*.txt");//Directory
///获取路径
//foreach (string _s in arrs)
//{
// Response.Write(_s + "<br/>");//读取完整物理路径
//}
//Response.Write("-----------------------------------------------------------------------" + "<br/>");
//foreach (string _s in arrs)
//{
// string _fname = Path.GetFileName(_s);//path类下的GetFileName
// Response.Write(_fname + "<br/>");//读取文件名
//}
//Response.Write("-----------------------------------------------------------------------" + "<br/>");
//foreach (string _s in arrs)
//{
// string _fname1 = Path.GetFileNameWithoutExtension(_s);
// Response.Write(_fname1 + "<br/>");//不带扩展名的文件名
//}
ListItem li;
foreach (string _s in arrs)
{
li = new ListItem();
string fname = Path.GetFileName(_s);
li.Text = fname;
DropDownList1.Items.Add(li);
}
}
}
protected void btn_read_Click(object sender, EventArgs e)
{
string _fname = DropDownList1.SelectedValue;
//Response.Write(_fname);
string _path =Path.Combine( MapPath("files"),_fname);
if(File.Exists(_path)){//判断是否存在,重要步骤
TextBox1.Text = File.ReadAllText(_path);//读取显示
}
}
protected void btn_save_Click(object sender, EventArgs e)
{
string _fname = DropDownList1.SelectedValue;//获取下拉框选择项
//Response.Write(_fname);
string _path = Path.Combine(MapPath("files"), _fname);//拼路径
string _content = TextBox1.Text;//获取文本框内容
File.WriteAllText(_path,_content);//写入源文件
}
}
aspx代码如下:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="文件读取.aspx.cs" Inherits="文件读取" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>
<asp:Button ID="btn_read" runat="server" Text="读取" οnclick="btn_read_Click" />
<asp:Button ID="btn_save" runat="server" Text="保存" οnclick="btn_save_Click" />
<br />
<asp:TextBox ID="TextBox1" runat="server" Height="216px" Width="218px" TextMode="MultiLine"></asp:TextBox>
</div>
</form>
</body>
</html>
效果如图: