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+"&nbsp;"+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;
}

转载于:https://www.cnblogs.com/Miton/archive/2011/06/01/2066028.html

ASP.NET文件操作收藏相关推荐

  1. asp.net 文件操作

    在ASP.NET中,文件处理的整个过程都是围绕着System.IO 这个名称空间展开的.这个名称空间中具有执行文件读.写所需要的类.Directory用于创建.移动和枚举通过目录和子目录,File用于 ...

  2. ASP.NET 文件操作类

    1.读取文件 2.写入文件 using System; using System.Collections.Generic; using System.IO; using System.Linq; us ...

  3. ASP.NET文件操作

    System.IO Directory:用于创建.移动和枚举通过目录和子目录 File:用于创建.复制.删除.移动和打开文件 Path:对包含文件或目录路径信息的String实例执行操作 Stream ...

  4. ASP.NET 文件操作实例

    //文件使用FileUpload打开 if (FileUpload1.HasFile)         {             try             { //流读取            ...

  5. Asp.Net_文件操作基类

    //读取,删除,批量拷贝,删除,写入,获取文件夹大小,文件属性,遍历目录 using System; using System.Data; using System.Configuration; us ...

  6. 【C/C++语言入门篇】-- 文件操作

    [C/C++语言入门篇]-- 文件操作 收藏 此文于2010-03-09被推荐到CSDN首页 如何被推荐? 最近实在是太忙了,这篇整整就推迟了1个月了,实在是对不起.之前本打算这个模块就结束了,文件操 ...

  7. C++的File类文件操作

    C++的File类文件操作 语言文件系统称为流文件(Stream),正文流(正文文件),二进制流(二进制文件) 缓冲与非缓冲文件 顺序操作文件与随机操作文件 顺序文件:读/写第K个数据块之前必须读/写 ...

  8. ASP.NET 如何操作文件

    本文由chenyangasp版权所有,可以转载,复制,粘贴,并请注明出处,但不得修改! 在asp.net操作文件的所有concept都在system.io  namespace中,这个namespac ...

  9. asp.net中各种类型文件解析 收藏

    asp.net中各种类型文件解析 收藏 ASP.NET的页面文件是*.aspx,每个页面对应一个*.resx资源文件和一个*.aspx.cs的代码文件. *.resx是资源文件.每个页面都有一个资源文 ...

最新文章

  1. java面向对象知识汇总的思维导图
  2. 计算机组成原lta,计算机组成原理实验三运算器
  3. qduoj - WHY吃糖果(二分套二分)
  4. 2、Collections操作(自定义类)的各种实现
  5. 极速体验:Oracle 18c 下载和Scalable Sequence新特性
  6. 点击出现遮罩层时滚动条会自己回到顶部_浅谈内容型信息流产品的“返回顶部”功能...
  7. 线性表建立学生信息表
  8. 瑞利信道,莱斯信道和高斯信道模型
  9. 常用计算机检索算符,计算机信息检索过程中常用的检索表达式
  10. 手把手教你接入支付宝支付
  11. 在深信服实习是怎样的体验(研发测试岗)
  12. 关灯后灯常亮、微亮、闪烁——多种原因分析
  13. js获取元素的属性值和获取元素内容
  14. Excel如何按照月份汇总销售量
  15. Network Security JumpStart
  16. python 批量读取csv_python批量读取csv文件
  17. GNS3思科模拟器:三层交换机技术
  18. 不用HR参与训练之盲视频超分中的自监督学习
  19. 2022年《北上广深杭》有哪些值得加入的软件测试大厂公司呢?花了三天三夜整理出各大互联网公司
  20. linux c 编程模板总结(一)

热门文章

  1. suse 11 oracle 10g,suse11+oracle10g安装
  2. 计算机类大一需要学什么原因,大一新生上大学要不要带电脑?我认为不论什么专业,电脑是必需品...
  3. stm32f4 hal 4位数码管_STM32裸机开发基础篇01开发环境搭建(HAL库)
  4. Python自动化办公之Excel对比工具
  5. 有感:仅在面试时攻克 MySQL 还不够
  6. 发现一个木马,竟然偷传我珍藏几十G的视频!
  7. 资源分享 | 统计学最全思维导图,附下载链接
  8. python显示range_python中range如何输出
  9. keil 在项目栏总有个叉_老股民的热心分享:均线金叉死叉买卖定式”,散户值得一看!...
  10. hashmap应用场景_京东4面(Java研发):事务隔离+乐观锁+HashMap+秒杀设计+微服务