貌似几天没写什么程序了,今天看了一下C#对文件的操作。。。
我学编程一向是先看数据库后看文件操作,寒一下 &_&!
还米写什么东西,这段代码基本上是书上看到的,贴在这供日后查阅吧~
前台:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Index.aspx.cs" Inherits="Index" %>
<!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:TextBox ID="tbCurrentDir" runat="server"></asp:TextBox><br />
当前目录为:<asp:Label ID="lblCurrentDir" runat="server"></asp:Label><br />
<asp:Table ID="tblDirInfo" runat="server">
</asp:Table>
</div>
</form>
</body>
</html>
代码:
using System;
using System.IO;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class Index : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string StrCurrentDir;
if (!IsPostBack)
{
StrCurrentDir = Server.MapPath(".");
lblCurrentDir.Text = StrCurrentDir;
tbCurrentDir.Text = StrCurrentDir;
}
else
{
StrCurrentDir = tbCurrentDir.Text.Trim();
lblCurrentDir.Text = StrCurrentDir;
tbCurrentDir.Text = StrCurrentDir;
}
FileInfo fi;
DirectoryInfo di;
TableCell td;
TableRow tr;
tr = new TableRow();
td = new TableCell();
td.Controls.Add(new LiteralControl("名称"));
tr.Cells.Add(td);
td = new TableCell();
td.Controls.Add(new LiteralControl("大小"));
tr.Cells.Add(td);
td = new TableCell();
td.Controls.Add(new LiteralControl("修改时间"));
tr.Cells.Add(td);
tblDirInfo.Rows.Add(tr);
string FileName;
string FileExt;
long FileSize;
DateTime FileModify;
try
{
DirectoryInfo dir = new DirectoryInfo(StrCurrentDir);
foreach (FileSystemInfo fsi in dir.GetFileSystemInfos())
{
FileName = "";
FileExt = "";
FileSize = 0;
if (fsi is FileInfo)
{
fi = (FileInfo)fsi;
FileName = fi.Name;
FileExt = fi.Extension;
FileSize = fi.Length;
FileModify = fi.LastWriteTime;
}
else
{
di = (DirectoryInfo)fsi;
FileName = di.Name + "...";
FileModify = di.LastWriteTime;
}
tr = new TableRow();
td = new TableCell();
td.Controls.Add(new LiteralControl(FileName));
tr.Cells.Add(td);
td = new TableCell();
td.Controls.Add(new LiteralControl(FileSize.ToString()));
tr.Cells.Add(td);
td = new TableCell();
td.Controls.Add(new LiteralControl(FileModify.ToString()));
tr.Cells.Add(td);
tblDirInfo.Rows.Add(tr);
}
}
catch (Exception)
{
Response.Write("<script>alert('你浏览的目录不存在!');history.back(-1);</script>");
}
}
}