ASP.NET文件操作收藏
System.IO
Directory:用于创建、移动和枚举通过目录和子目录
File:用于创建、复制、删除、移动和打开文件
Path:对包含文件或目录路径信息的String实例执行操作
StreamReader、StreamWriter:以一种特定的编码写字符
File类常用的方法
AppendText:创建一个StreamWriter对象,用于在指定文件的末尾添加新的内容
Copy:复制指定文件
Move:移动文件
Delete:删除文件
Exit:判断指定文件是否存在
Open:以指定的方式、权限打开指定文件
OpenRead:以只读方式打开指定文件
OpenText:打开文本文件,返回流
OpenWrite:以读写方式打开指定文件
Cteate:创建一个指定文件
CreateText:创建一个文本文件
File类的使用
using System.IO;
using System.Text;
private void Page_Load(object sender, System.EventArgs e)
{
//建立StreamWriter为写做准备
StreamWriter rw = File.CreateText(Server.MapPath(".")+"\\CreateText.txt");
//使用WriteLine写入内容
rw.WriteLine("使用File.CreateText 方法");
rw.WriteLine("返回StreamWriter流,利用这个流进行写入。");
//将缓冲区的内容写入文件
rw.Flush();
//关闭rw对象
rw.Close();
//打开文本文件
StreamReader sr = File.OpenText(Server.MapPath(".")+"\\CreateText.txt");
StringBuilder output = new StringBuilder();
string rl;
while((rl=sr.ReadLine())!=null)
{
output.Append(rl+"<br>");
}
lblFile.Text = output.ToString();
sr.Close();
}
using System.IO;
using System.Text;
private void btnRead_Click(object sender, System.EventArgs e)
{
//打开文本文件
string strFileName = FileSelect.PostedFile.FileName;
if(Path.GetFileName(strFileName)=="")
return;
StreamReader sr = File.OpenText(strFileName);
StringBuilder output = new StringBuilder();
string rl;
while((rl=sr.ReadLine())!=null)
{
output.Append(rl+"<br>");
}
lblFile.Text = output.ToString();
sr.Close();
}
文件复制
private void Page_Load(object sender, System.EventArgs e)
{
string OrignFile= Server.MapPath(".")+"\\CreateText.txt";
string NewFile = Server.MapPath(".")+"\\NewCreateText.txt";
//首先判断源文件和新文件是否都存在
if(File.Exists(OrignFile))
{
lblBFromFile.Text = OrignFile + "存在<br>";
}
else
{
lblBFromFile.Text = OrignFile + "不存在<br>";
}
if(File.Exists(NewFile))
{
lblBToFile.Text = NewFile + "存在<br>";
}
else
{
lblBToFile.Text = NewFile + "不存在<br>";
}
}
private void btnCopy_Click(object sender, System.EventArgs e)
{
string OrignFile= Server.MapPath(".")+"\\CreateText.txt";
string NewFile = Server.MapPath(".")+"\\NewCreateText.txt";
//拷贝文件
try
{
File.Copy(OrignFile,NewFile);
if(File.Exists(OrignFile))
{
lblEFromFile.Text = OrignFile + "存在<br>";
}
else
{
lblEFromFile.Text = OrignFile + "不存在<br>";
}
if(File.Exists(NewFile))
{
FileInfo fi = new FileInfo(NewFile);
DateTime Ctime = fi.CreationTime;
lblEToFile.Text = NewFile + "已经存在<br>创建时间:" + Ctime.ToString() + "<br>";
}
else
{
lblEToFile.Text = NewFile + "不存在<br>";
}
}
catch(Exception ee)
{
lblError.Text = "不能拷贝文件,错误信息为:"+ee.Message;
}
}
private void Page_Load(object sender, System.EventArgs e)
{
string OrignFile,NewFile;
OrignFile = Server.MapPath(".")+"\\CreateText.txt";
NewFile = Server.MapPath(".")+"\\..\\NewCreateText.txt";
//首先判断源文件和新文件是否都存在
if(File.Exists(OrignFile))
{
lblBFromFile.Text = OrignFile + "存在<br>";
}
else
{
lblBFromFile.Text = OrignFile + "不存在<br>";
}
if(File.Exists(NewFile))
{
lblBToFile.Text = NewFile + "存在<br>";
}
else
{
lblBToFile.Text = NewFile + "不存在<br>";
}
}
private void btnMove_Click(object sender, System.EventArgs e)
{
string OrignFile,NewFile;
OrignFile = Server.MapPath(".")+"\\CreateText.txt";
NewFile = Server.MapPath(".")+"\\..\\NewCreateText.txt";
//移动文件
try
{
File.Move(OrignFile,NewFile);
if(File.Exists(OrignFile))
{
lblEFromFile.Text = OrignFile + "存在<br>";
}
else
{
lblEFromFile.Text = OrignFile + "不存在<br>";
}
if(File.Exists(NewFile))
{
FileInfo fi = new FileInfo(NewFile);
DateTime Ctime = fi.CreationTime;
lblEToFile.Text = NewFile + "已经存在了<br>创建时间:" + Ctime.ToString() + "<br>";
}
else
{
lblEToFile.Text = NewFile + "不存在<br>";
}
}
catch(Exception ee)
{
lblError.Text = "不能移动文件";
}
}
private void btnDelete_Click(object sender, System.EventArgs e)
{
//首先判断文件是否存在
string delFile = Server.MapPath(".")+"\\NewCreateText.txt";
if(File.Exists(delFile))
{
//建立FileInfo对象,取得指定的文件信息
FileInfo fi = new FileInfo(delFile);
DateTime CreateTime = fi.CreationTime;
Label lblOne = new Label();
lblOne.Text = delFile + "存在<br>创建时间为:" + CreateTime.ToString() + "<p>";
plShow.Controls.Add(lblOne);
try
{
//删除文件
File.Delete(delFile);
Label lblOk = new Label();
lblOk.Text = "删除文件"+delFile+"成功";
plShow.Controls.Add(lblOk);
}
catch(Exception ee)
{
//捕捉异常
Label lblFileExists = new Label();
lblFileExists.Text = "不能删除文件"+delFile+"<br>";
plShow.Controls.Add(lblFileExists);
}
}
else
{
Label lblError = new Label();
lblError.Text = delFile + "根本就不存在";
plShow.Controls.Add(lblError);
}
}
FileSteam常用属性和方法
CanRead:判断当前是否支持读取
Canwrite:判断当前是否支持写入
CanSeek:是否支持搜索
IsAsync:是否处于异步打开模式
Postion:设置获取当前流所处位置
Flush:将当前缓存区的数据写入文件
Lock:锁定流,防止其他文件访问
Seek:设置当前流操作的指针位置
FileSteam类的使用
private void Page_Load(object sender, System.EventArgs e)
{
FileStream fs = new FileStream(Server.MapPath(".")+"\\FileStreamCreateText.txt",FileMode.Create,FileAccess.Write);
//建立StreamWriter为写做准备
StreamWriter rw = new StreamWriter(fs,Encoding.Default);
//使用WriteLine写入内容
rw.WriteLine("曾经有一份真挚的爱情放在我的面前。");
rw.WriteLine("而我没有珍惜,当我失去的时候,我才追悔莫及。");
rw.WriteLine("人世间最大的痛苦莫过于此,如果上天给我一个再来一次的机会。");
rw.WriteLine("我会对那个女孩说三个字:\"我爱你。\"");
rw.WriteLine("如果非要在这份爱上加一个期限的话,我希望是一万年。");
//将缓冲区的内容写入文件
rw.Flush();
//关闭rw对象
rw.Close();
fs.Close();
fs = new FileStream(Server.MapPath(".")+"\\FileStreamCreateText.txt",FileMode.Open,FileAccess.Read);
//打开文本文件
StreamReader sr = new StreamReader(fs,Encoding.Default);
StringBuilder output = new StringBuilder();
string rl;
while((rl=sr.ReadLine())!=null)
{
output.Append(rl+"<br>");
}
lblFile.Text = output.ToString();
sr.Close();
fs.Close();
}
private void btnRead_Click(object sender, System.EventArgs e)
{
//打开文本文件
string strFileName = FileSelect.PostedFile.FileName;
if(Path.GetFileName(strFileName)=="")
return;
FileStream fs = new FileStream(strFileName,FileMode.Open,FileAccess.Read);
StreamReader sr = new StreamReader(fs,Encoding.Default);
StringBuilder output = new StringBuilder();
string rl;
while((rl=sr.ReadLine())!=null)
{
output.Append(rl+"<br>");
}
sr.Close();
fs.Close();
lblFile.Text = output.ToString();
}
private void btnCopy_Click(object sender, System.EventArgs e)
{
string OriginFile = FileSelect.PostedFile.FileName;
string NewFile = tbDes.Text +"\\"+Path.GetFileName(OriginFile);
//下面开始操作
//建立两个FileStream对象
FileStream fsOF = new FileStream(OriginFile,FileMode.Open,FileAccess.Read);
FileStream fsNF = new FileStream(NewFile,FileMode.Create,FileAccess.Write);
//建立分别建立一个读写类
BinaryReader br = new BinaryReader(fsOF);
BinaryWriter bw = new BinaryWriter(fsNF);
//将读取文件流指针指向流的头部
br.BaseStream.Seek(0,SeekOrigin.Begin);
//将写入文件流指针指向流的尾部
bw.BaseStream.Seek(0,SeekOrigin.End);
while(br.BaseStream.Position < br.BaseStream.Length)
{
//从br流中读取一个Byte并马上写入bw流
bw.Write(br.ReadByte());
}
br.Close();
bw.Close();
//操作后判断源文件是否存在
if(File.Exists(NewFile))
{
lbInfo.Text = "附件复制成功!";
}
else
{
lbInfo.Text = "文件复制失败!";
}
}
DirectoryInto和FileInfo类的使用
private void Page_Load(object sender, System.EventArgs e)
{
string strCurrentDir;
//初始化一些数据
if(!Page.IsPostBack)
{
strCurrentDir = Server.MapPath(".");
lblCurrentDir.Text = strCurrentDir;
tbCurrentDir.Text = strCurrentDir;
}
else
{
strCurrentDir = tbCurrentDir.Text;
tbCurrentDir.Text = strCurrentDir;
lblCurrentDir.Text = strCurrentDir;
}
FileInfo fi;
DirectoryInfo di;
TableCell td;
TableRow tr;
/* 设定Table中的数据首先搞定第一行 */
tr = new TableRow();
td = new TableCell();
td.Controls.Add(new LiteralControl("<img src='name.gif'>"));
tr.Cells.Add(td);
td = new TableCell();
td.Controls.Add(new LiteralControl("<img src='size.gif'>"));
tr.Cells.Add(td);
td = new TableCell();
td.Controls.Add(new LiteralControl("<img src='lastmodify.gif'>"));
tr.Cells.Add(td);
tbDirInfo.Rows.Add(tr);
string FileName; //文件名称
string FileExt; //文件扩展名
string FilePic; //文件图片
long FileSize; //文件大小
DateTime FileModify; //文件更新时间
DirectoryInfo dir = new DirectoryInfo(strCurrentDir);
foreach(FileSystemInfo fsi in dir.GetFileSystemInfos())
{
FilePic = "";
FileName = "";
FileExt = "";
FileSize = 0;
if(fsi is FileInfo)
{
//表示当前fsi是文件
fi = (FileInfo)fsi;
FileName = fi.Name;
FileExt = fi.Extension;
FileSize = fi.Length;
FileModify = fi.LastWriteTime;
//通过扩展名来选择文件显示图标
switch(FileExt)
{
case ".gif":
FilePic = "gif.gif";
break;
default:
FilePic = "other.gif";
break;
}
FilePic = "<img src='"+FilePic+"' width=25 height=20>";
}
else
{
//当前为目录
di = (DirectoryInfo)fsi;
FileName = di.Name;
FileModify = di.LastWriteTime;
FilePic = "<img src='directory.gif' width=25 height=20>";
}
//组建新的行
tr = new TableRow();
td = new TableCell();
td.Controls.Add(new LiteralControl(FilePic+" "+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);
tbDirInfo.Rows.Add(tr);
}
}
private void btnFind_Click(object sender, System.EventArgs e)
{
try
{
if(tbInput.Text.Trim()=="")
{
lbPath.Text = "文件名为空!";
return;
}
string[] drives = System.IO.Directory.GetLogicalDrives();
foreach (string str in drives)
{
if(ProcessDirectory(str))
break;
}
if(!bExist)
lbPath.Text = "不存在此文件!";
}
catch (System.IO.IOException)
{
Response.Write("I/O错误!");
}
catch (System.Security.SecurityException)
{
Response.Write("没有访问权限!");
}
}
public bool ProcessDirectory(string targetDirectory)
{
try
{
// Process the list of files found in the directory
string [] fileEntries = Directory.GetFiles(targetDirectory);
foreach(string fileName in fileEntries)
{
if(ProcessFile(fileName))
return true;
}
// Recurse into subdirectories of this directory
string [] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
foreach(string subdirectory in subdirectoryEntries)
{
if(ProcessDirectory(subdirectory))
return true;
}
return false;
}
catch(Exception)
{
return false;
}
}
public bool ProcessFile(string strFileName)
{
if(Path.GetFileName(strFileName).ToLower()==tbInput.Text.Trim().ToLower())
{
lbPath.Text = strFileName.ToLower();
bExist=true;
return true;
}
else
return false;
}