Asp.Net文件处理

来源:互联网 发布:linux下数据库备份 编辑:程序博客网 时间:2024/05/27 03:26
Asp.Net文件处理
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:然后后台编码:
 1using System;
 2using System.Collections;
 3using System.ComponentModel;
 4using System.Data;
 5using System.Drawing;
 6using System.Web;
 7using System.Web.SessionState;
 8using System.Web.UI;
 9using System.Web.UI.WebControls;
10using System.Web.UI.HtmlControls;
11using System.IO;
12using System.Text;
13namespace AspFile.File
14{
15    public partial class FileCreateText : System.Web.UI.Page
16    {
17        protected void Page_Load(object sender, EventArgs e)
18        {
19            //建立StreamWriter为写做准备
20            StreamWriter rw =System.IO.File.CreateText(Server.MapPath(".") + "/CreateText.txt");
21            //使用WriteLine写入内容
22            rw.WriteLine("使用File.CreateText 方法");
23            rw.WriteLine("返回StreamWriter流,利用这个流进行写入。");
24            //将缓冲区的内容写入文件
25            rw.Flush();
26            //关闭rw对象
27            rw.Close();
28            //打开文本文件
29            StreamReader sr =System.IO.File.OpenText(Server.MapPath(".") + "/CreateText.txt");
30            StringBuilder output = new StringBuilder();
31            string rl;
32            while ((rl = sr.ReadLine()) != null)
33            {
34                output.Append(rl + "<br>");
35            }

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

39    }

40}
第二个是读取txt文件,我们就读我们刚才建立那个文件,因为都是使用utf-8编码所以读那个不出现乱码。用FileStream方法可以设置编码,我们后边会说到。
这个页面是放一个HTML控件InputFile那个,然后放个BUTTON来查看LABEL生成的文本。
编码如下:
 1using System;
 2using System.Data;
 3using System.Configuration;
 4using System.Collections;
 5using System.Web;
 6using System.Web.Security;
 7using System.Web.UI;
 8using System.Web.UI.WebControls;
 9using System.Web.UI.WebControls.WebParts;
10using System.Web.UI.HtmlControls;
11using System.IO;
12using System.Text;
13namespace AspFile.File
14{
15    public partial class FileOpen : System.Web.UI.Page
16    {
17        protected void Page_Load(object sender, EventArgs e)
18        {
19        }

20        protected void Button1_Click(object sender, EventArgs e)
21        {
22            //打开文本文件
23            string strFileName = FileOpenFile.PostedFile.FileName;
24            if (Path.GetFileName(strFileName) == "")
25                return;
26            StreamReader sr = System.IO.File.OpenText(strFileName);
27            StringBuilder output = new StringBuilder();
28            string rl;
29            while ((rl = sr.ReadLine()) != null)
30            {
31                output.Append(rl + "<br>");
32            }

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

36    }

37}

第三个例子就是拷贝和移动了,为什么放一起说呢,因为这两个你操作时候只需要修改一个小小的地方就可以了,System.IO.File.Copy这里换成Move:
 1<form id="form1" runat="server">
 2    <div>
 3        <h1>拷贝操作前</h1>
 4        <asp:Button ID="btnCopy" runat="server" Text="Copy" OnClick="btnCopy_Click" /><br>
 5        <asp:Label id="lblBFromFile" runat="server" /><br>
 6        <asp:Label id="lblBToFile" runat="server" /><br>
 7        <h1>拷贝操作后</h1>
 8        <asp:Label id="lblEFromFile" runat="server" /><br>
 9        <asp:Label id="lblEToFile" runat="server" /><br>
10        <asp:Label id="lblError" runat="server" />
11    </div>
12</form>
后台编码:
 1using System;
 2using System.Data;
 3using System.Configuration;
 4using System.Collections;
 5using System.Web;
 6using System.Web.Security;
 7using System.Web.UI;
 8using System.Web.UI.WebControls;
 9using System.Web.UI.WebControls.WebParts;
10using System.Web.UI.HtmlControls;
11using System.IO;
12using System.Text;
13
14namespace AspFile.File
15{
16    public partial class FileCopy : System.Web.UI.Page
17    {
18        protected void Page_Load(object sender, EventArgs e)
19        {
20            //指定源文件和新文件
21            string orignFile = Server.MapPath(".") + "/CreateText.txt";
22            string newFile = Server.MapPath(".") + "/NewCreateText.txt";
23            //判断源文件和新文件是否存在
24            if (System.IO.File.Exists(orignFile))
25            {
26                lblBFromFile.Text = orignFile + "存在";
27            }

28            else
29            {
30                lblBFromFile.Text = orignFile + "不存在";
31            }

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

36            else
37            {
38                lblBToFile.Text = newFile + "不存在";
39            }

40        }

41        protected void btnCopy_Click(object sender, EventArgs e)
42        {
43            string OrignFile = Server.MapPath(".") + "/CreateText.txt";
44            string NewFile = Server.MapPath(".") + "/NewCreateText.txt";
45            //拷贝文件
46            try
47            {
48                System.IO.File.Copy(OrignFile, NewFile);
49                if (System.IO.File.Exists(OrignFile))
50                {
51                    lblEFromFile.Text = OrignFile + "存在<br>";
52                }

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

57                if (System.IO.File.Exists(NewFile))
58                {
59                    FileInfo fi = new FileInfo(NewFile);
60                    DateTime Ctime = fi.CreationTime;
61                    lblEToFile.Text = NewFile + "已经存在<br>创建时间:" + Ctime.ToString() + "<br>";
62                }

63                else
64                {
65                    lblEToFile.Text = NewFile + "不存在<br>";
66                }

67            }

68            catch (Exception ex)
69            
72        }

73    }

74}

最后一个是删除测试:放个button放个panel来显示信息。
后台编码:
 1using System;
 2using System.Data;
 3using System.Configuration;
 4using System.Collections;
 5using System.Web;
 6using System.Web.Security;
 7using System.Web.UI;
 8using System.Web.UI.WebControls;
 9using System.Web.UI.WebControls.WebParts;
10using System.Web.UI.HtmlControls;
11using System.IO;
12using System.Text;
13namespace AspFile.File
14{
15    public partial class FileDel : System.Web.UI.Page
16    {
17        protected void Page_Load(object sender, EventArgs e)
18        {
19        }

20        protected void btnDelete_Click(object sender, EventArgs e)
21        {
22            //首先判断文件是否存在
23            string delFile = Server.MapPath(".") + "/NewCreateText.txt";
24            if (System.IO.File.Exists(delFile))
25            {
26                //建立FileInfo对象,取得指定的文件信息
27                FileInfo fi = new FileInfo(delFile);
28                DateTime CreateTime = fi.CreationTime;
29                Label lblOne = new Label();
30                lblOne.Text = delFile + "存在<br>创建时间为:" + CreateTime.ToString() + "<p>";
31                plShow.Controls.Add(lblOne);
32                try
33                {
34                    //删除文件
35                    System.IO.File.Delete(delFile);
36                    Label lblOk = new Label();
37                    lblOk.Text = "删除文件" + delFile + "成功";
38                    plShow.Controls.Add(lblOk);
39                }

40                catch (Exception ee)
41                {
42                    //捕捉异常
43                    Label lblFileExists = new Label();
44                    lblFileExists.Text = "不能删除文件" + delFile + "<br>";
45                    plShow.Controls.Add(lblFileExists);
46                }

47            }

48            else
49            {
50                Label lblError = new Label();
51                lblError.Text = delFile + "根本就不存在";
52                plShow.Controls.Add(lblError);
53            }

54        }

55    }

56}
FileStream:
FileStream 对于在文件系统上读取和写入文件非常有用, FileStream 缓存输入和输出,以获得更好的性能。
FileStream 类能够以同步或异步这两种模式之一打开文件,而且对同步方法(Read 和Write)和异步方法(BeginRead 和BeginWrite)有显著的性能影响。
在Windows系统中,如果输入输出数据小于64KB,则采用同步模式性能较好;而当大于64KB时,则最好采用异步模式。
FileSteam常用属性和方法:
• CanRead:判断当前流是否支持读取。
• CanWrite:判断当前流是否支持写入。
• CanSeek:是否支持搜索。
• IsAsync:是否处于异步打开模式。
• Postion:设置获取当前流所处位置。
• Flush:将当前缓存区的数据写入文件。
• Lock:锁定流,防止其他文件访问。
• Seek:设置当前流操作的指针位置。
还是来看例子来加深理解吧
第一个例子,FileStream来创建文件,页面就放一个Label就行了
后台编码:
 1using System;
 2using System.Data;
 3using System.Configuration;
 4using System.Collections;
 5using System.Web;
 6using System.Web.Security;
 7using System.Web.UI;
 8using System.Web.UI.WebControls;
 9using System.Web.UI.WebControls.WebParts;
10using System.Web.UI.HtmlControls;
11using System.IO;
12using System.Text;
13namespace AspFile.FileStream
14{
15    public partial class FileStreamCreate : System.Web.UI.Page
16    {
17        protected void Page_Load(object sender, EventArgs e)
18        {
19            System.IO.FileStream fs = new System.IO.FileStream(Server.MapPath(".") + "/FileStreamCreateText.txt", FileMode.Create, FileAccess.Write);
20            //建立StreamWriter为写做准备
21            StreamWriter rw = new StreamWriter(fs, Encoding.Default);
22            //使用WriteLine写入内容
23            rw.WriteLine("曾经有一份真挚的爱情放在我的面前。");
24            rw.WriteLine("而我没有珍惜,当我失去的时候,我才追悔莫及。");
25            rw.WriteLine("人世间最大的痛苦莫过于此,如果上天给我一个再来一次的机会。");
26            rw.WriteLine("我会对那个女孩说三个字:"我爱你。"");
27            rw.WriteLine("如果非要在这份爱上加一个期限的话,我希望是一万年。");
28            //将缓冲区的内容写入文件
29            rw.Flush();
30            //关闭rw对象
31            rw.Close();
32            fs.Close();
33            fs = new System.IO.FileStream(Server.MapPath(".") + "/FileStreamCreateText.txt", FileMode.Open, FileAccess.Read);
34            //打开文本文件
35            StreamReader sr = new StreamReader(fs, Encoding.Default);
36            StringBuilder output = new StringBuilder();
37            string rl;
38            while ((rl = sr.ReadLine()) != null)
39            {
40                output.Append(rl + "<br>");
41            }

42            lblFile.Text = output.ToString();
43            sr.Close();
44            fs.Close();
45        }

46    }

47}
第二个例子是读文件,注意这里就可以解决File下操作中的乱码问题,因为FileStream下边可以设置编码
放个选择文件的控件,一个按钮一个label。后台编码:
 1protected void Button1_Click(object sender, EventArgs e)
 2{
 3    string strFileStream;
 4    strFileStream = File1.PostedFile.FileName;
 5    if (Path.GetFileName(strFileStream) == "")
 6        return;
 7    System.IO.FileStream fs = new System.IO.FileStream(strFileStream,FileMode.Open,FileAccess.Read);
 8    //这里就可以设置编码,我们在这里指定的是系统默认的编码。
 9    StreamReader sr = new StreamReader(fs, Encoding.Default);
10    StringBuilder output = new StringBuilder();
11    string rl;
12    while ((rl = sr.ReadLine()) != null)
13    {
14        output.Append(rl + "<br>");
15    }

16    sr.Close();
17    fs.Close();
18    Label1.Text = output.ToString();
19}
第三个例子是可以进行流的复制文件。
添加html的inputfile控件,按钮,要复制到的路径,label。注意要复制到的地方必须具有写入操作的权限。
后台编码如下:
 1using System;
 2using System.Data;
 3using System.Configuration;
 4using System.Collections;
 5using System.Web;
 6using System.Web.Security;
 7using System.Web.UI;
 8using System.Web.UI.WebControls;
 9using System.Web.UI.WebControls.WebParts;
10using System.Web.UI.HtmlControls;
11using System.IO;
12using System.Text;
13namespace AspFile.FileStream
14{
15    public partial class FileStreamCopy : System.Web.UI.Page
16    {
17        protected void Page_Load(object sender, EventArgs e)
18        {
19        }

20        protected void btnCopy_Click(object sender, EventArgs e)
21        {
22            string OriginFile = FileSelect.PostedFile.FileName;
23            string NewFile = tbDes.Text + "/" + Path.GetFileName(OriginFile);
24            //下面开始操作
25            //建立两个FileStream对象
26            System.IO.FileStream fsOF = new System.IO.FileStream(OriginFile, FileMode.Open, FileAccess.Read);
27            System.IO.FileStream fsNF = new System.IO.FileStream(NewFile, FileMode.Create, FileAccess.Write);
28            //建立分别建立一个读写类
29            BinaryReader br = new BinaryReader(fsOF);
30            BinaryWriter bw = new BinaryWriter(fsNF);
31            //将读取文件流指针指向流的头部
32            br.BaseStream.Seek(0, SeekOrigin.Begin);
33            //将写入文件流指针指向流的尾部
34            bw.BaseStream.Seek(0, SeekOrigin.End);
35            while (br.BaseStream.Position < br.BaseStream.Length)
36            {
37                //从br流中读取一个Byte并马上写入bw流
38                bw.Write(br.ReadByte());
39            }

40            br.Close();
41            bw.Close();
42            //操作后判断源文件是否存在
43            if (System.IO.File.Exists(NewFile))
44            {
45                lbInfo.Text = "附件复制成功!";
46            }

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

51        }

52    }

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