代码改变世界

Asp.Net文件处理

2007-09-01 13:52  Yeemio  阅读(1436)  评论(2编辑  收藏  举报
MSDN的WEBCAST,感觉单纯看一遍意义不大,做个笔记,以备不时只需查找方便。代码部分本人在XP+VS2005+SQL2005测试通过,请大家指教。

这篇笔记呢,例子比较多,希望大家都能举一反三。

文件操作概述:
任何一种编程技术,都少不了对文件的操作。
由于ASP.NET使用了.NET平台同一的类库,因而其对文件的操作的功能非常强大.
.NET提供了一些专门用于文件操作的类库,比如File\FileStream\BinaryReader\BinaryWriter\StreamReader\StreamWriter等等。

文件和流:
文件:存储在介质上的永久数据的有序集合,它是进行数据读写操作的基本对象。每个文件都拥有一些基本属性,如文件名、存放路径、访问权限等。
流:提供了连续的字节流存放空间,它也是数据读写操作的基本对象。流中存放的数据空间可以是不连续的,甚至可以分布在多个地方。

ASP.NET中文件操作中当然要引用System.IO这个名称空间:
•Directory :用于创建、移动和枚举通过目录和子目录。
•File :用于创建、复制、删除、移动和打开文件。
•Path:对包含文件或目录路径信息的String 实例执行操作。
•StreamReader、StreamWriter:以一种特定的编码读写字符。


File类:
•提供用于创建、复制、删除、移动和打开文件的静态方法,并协助创建FileStream对象。
•File 类的所有方法都是静态的,因而无需具有文件的实例就可被调用。

File类常用方法:
•AppendText:创建一个SteamWriter对象用于在指定文件的末尾添加新的内容。
•Copy:复制指定文件。
•Move:移动文件。
•Delete:删除文件。
•Exist:判断指定文件是否存在。
•Open:以指定的方式、权限打开指定文件。
•OpenRead:以只读方式打开指定文件。
•OpenText:打开文本文件,返回流。
•OpenWrite:以读写方式打开指定文件。
•Cteate:创建一个指定文件。
• CreateText:创建一个文本文件。

我们来看下边一些例子来了解File类的基本的使用:
第一个例子是建立一个Txt文件。建立一个页面,添加一个lable:然后后台编码:

 

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Text;

namespace AspFile.File
{
    
public partial class FileCreateText : System.Web.UI.Page
    
{
        
protected void Page_Load(object sender, EventArgs e)
        
{
            
//建立StreamWriter为写做准备
            StreamWriter rw =System.IO.File.CreateText(Server.MapPath("."+ "\\CreateText.txt");
            
//使用WriteLine写入内容
            rw.WriteLine("使用File.CreateText 方法");
            rw.WriteLine(
"返回StreamWriter流,利用这个流进行写入。");
            
//将缓冲区的内容写入文件
            rw.Flush();
            
//关闭rw对象
            rw.Close();

            
//打开文本文件
            StreamReader sr =System.IO.File.OpenText(Server.MapPath("."+ "\\CreateText.txt");
            StringBuilder output 
= new StringBuilder();
            
string rl;
            
while ((rl = sr.ReadLine()) != null)
            
{
                output.Append(rl 
+ "<br>");
            }

            Label1.Text 
= output.ToString();
            sr.Close();
        }

    }

}

 

第二个是读取txt文件,我们就读我们刚才建立那个文件,因为都是使用utf-8编码所以读那个不出现乱码。用FileStream方法可以设置编码,我们后边会说到。
这个页面是放一个HTML控件InputFile那个,然后放个BUTTON来查看LABEL生成的文本。
编码如下:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
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;
using System.IO;
using System.Text;

namespace AspFile.File
{
    
public partial class FileOpen : System.Web.UI.Page
    
{
        
protected void Page_Load(object sender, EventArgs e)
        
{

        }


        
protected void Button1_Click(object sender, EventArgs e)
        
{
            
//打开文本文件
            string strFileName = FileOpenFile.PostedFile.FileName;
            
if (Path.GetFileName(strFileName) == "")
                
return;
            StreamReader sr 
= System.IO.File.OpenText(strFileName);
            StringBuilder output 
= new StringBuilder();
            
string rl;
            
while ((rl = sr.ReadLine()) != null)
            
{
                output.Append(rl 
+ "<br>");
            }

            Label1.Text 
= output.ToString();
            sr.Close();
        }

    }

}

第三个例子就是拷贝和移动了,为什么放一起说呢,因为这两个你操作时候只需要修改一个小小的地方就可以了,System.IO.File.Copy这里换成Move:
<form id="form1" runat="server">
    <div>
        <h1>拷贝操作前</h1>
    <asp:Button ID="btnCopy" runat="server" Text="Copy" OnClick="btnCopy_Click" /><br>
    <asp:Label id="lblBFromFile" runat="server" /><br>
 <asp:Label id="lblBToFile" runat="server" /><br>
 <h1>拷贝操作后</h1>
 <asp:Label id="lblEFromFile" runat="server" /><br>
 <asp:Label id="lblEToFile" runat="server" /><br>
 <asp:Label id="lblError" runat="server" />
    </div>
    </form>

后台编码:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
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;
using System.IO;
using System.Text;


namespace AspFile.File
{
    
public partial class FileCopy : System.Web.UI.Page
    
{
        
protected void Page_Load(object sender, EventArgs e)
        
{
            
//指定源文件和新文件
            string orignFile = Server.MapPath("."+ "\\CreateText.txt";
            
string newFile = Server.MapPath("."+ "\\NewCreateText.txt";
            
//判断源文件和新文件是否存在
            if (System.IO.File.Exists(orignFile))
            
{
                lblBFromFile.Text 
= orignFile + "存在";

            }

            
else
            
{
                lblBFromFile.Text 
= orignFile + "不存在";
            }

            
if (System.IO.File.Exists(newFile))
            
{
                lblBToFile.Text 
= newFile + "存在";
            }

            
else
            
{
                lblBToFile.Text 
= newFile + "不存在";
            }

        }


        
protected void btnCopy_Click(object sender, EventArgs e)
        
{
            
string OrignFile = Server.MapPath("."+ "\\CreateText.txt";
            
string NewFile = Server.MapPath("."+ "\\NewCreateText.txt";
            
//拷贝文件
            try
            
{
                System.IO.File.Copy(OrignFile, NewFile);
                
if (System.IO.File.Exists(OrignFile))
                
{
                    lblEFromFile.Text 
= OrignFile + "存在<br>";
                }

                
else
                
{
                    lblEFromFile.Text 
= OrignFile + "不存在<br>";
                }


                
if (System.IO.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 ex)
            
{
                lblError.Text 
= "不能拷贝文件,错误信息为:" + ex.Message;
            }


        }

    }

}

最后一个是删除测试:放个button放个panel来显示信息。
后台编码:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
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;
using System.IO;
using System.Text;

namespace AspFile.File
{
    
public partial class FileDel : System.Web.UI.Page
    
{
        
protected void Page_Load(object sender, EventArgs e)
        
{

        }


        
protected void btnDelete_Click(object sender, EventArgs e)
        
{
            
//首先判断文件是否存在
            string delFile = Server.MapPath("."+ "\\NewCreateText.txt";
            
if (System.IO.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
                
{
                    
//删除文件
                    System.IO.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);
            }

        }

    }

}


FileStream:
FileStream 对于在文件系统上读取和写入文件非常有用, FileStream 缓存输入和输出,以获得更好的性能。
FileStream 类能够以同步或异步这两种模式之一打开文件,而且对同步方法(Read 和Write)和异步方法(BeginRead 和BeginWrite)有显著的性能影响。
在Windows系统中,如果输入输出数据小于64KB,则采用同步模式性能较好;而当大于64KB时,则最好采用异步模式。

FileSteam常用属性和方法:
• CanRead:判断当前流是否支持读取。
• CanWrite:判断当前流是否支持写入。
• CanSeek:是否支持搜索。
• IsAsync:是否处于异步打开模式。
• Postion:设置获取当前流所处位置。
• Flush:将当前缓存区的数据写入文件。
• Lock:锁定流,防止其他文件访问。
• Seek:设置当前流操作的指针位置。

还是来看例子来加深理解吧
第一个例子,FileStream来创建文件,页面就放一个Label就行了
后台编码:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
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;
using System.IO;
using System.Text;

namespace AspFile.FileStream
{
    
public partial class FileStreamCreate : System.Web.UI.Page
    
{
        
protected void Page_Load(object sender, EventArgs e)
        
{
            System.IO.FileStream fs 
= new System.IO.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 System.IO.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();
        }

    }

}

第二个例子是读文件,注意这里就可以解决File下操作中的乱码问题,因为FileStream下边可以设置编码
放个选择文件的控件,一个按钮一个label。后台编码:

protected void Button1_Click(object sender, EventArgs e)
        
{
            
string strFileStream;
            strFileStream 
= File1.PostedFile.FileName;
            
if (Path.GetFileName(strFileStream) == "")
                
return;
            System.IO.FileStream fs 
= new System.IO.FileStream(strFileStream,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();
            Label1.Text 
= output.ToString();
        }

第三个例子是可以进行流的复制文件。
添加html的inputfile控件,按钮,要复制到的路径,label。注意要复制到的地方必须具有写入操作的权限。
后台编码如下:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
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;
using System.IO;
using System.Text;
namespace AspFile.FileStream
{
    
public partial class FileStreamCopy : System.Web.UI.Page
    
{
        
protected void Page_Load(object sender, EventArgs e)
        
{

        }


        
protected void btnCopy_Click(object sender, EventArgs e)
        
{
            
string OriginFile = FileSelect.PostedFile.FileName;
            
string NewFile = tbDes.Text + "\\" + Path.GetFileName(OriginFile);

            
//下面开始操作

            
//建立两个FileStream对象
            System.IO.FileStream fsOF = new System.IO.FileStream(OriginFile, FileMode.Open, FileAccess.Read);
            System.IO.FileStream fsNF 
= new System.IO.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 (System.IO.File.Exists(NewFile))
            
{
                lbInfo.Text 
= "附件复制成功!";
            }

            
else
            
{
                lbInfo.Text 
= "文件复制失败!";
            }

        }

    }

}



DirectoryInfo和FileInfo类:
• Directory(File) 类的所有方法都是静态的,因而无需具有目录的实例就可被调用。DirectoryInfo (FileInfo)类只包含实例方法。
• Directory (File)类的静态方法对所有方法执行安全检查。如果打算多次重用一个对象,请考虑改用DirectoryInfo(FileInfo)的相应实例方法,因为安全检查并不总是必要的。
这些例子都很简单,大家可以参照上边的例子自己做一下。然后最后还有个网络资源管理器的例子,这个篇幅太大了,这里我就不说明了。有想要最后网络管理器例子的朋友请给我留言,或者自己去MSDN下载。