File类与FileInfo类的区别

这些年代码也写了不少,关于文件I/O的操作也写了很多,基本上File类与FileInfo类也没有刻意的去看性能,有时用着也挺糊涂的,今天就将这些I/0操作总结下,老样子贴码

首先先了解清楚下File类与FileInfo类的定义:

File类:

引用命名空间:using System.IO;

File 类用于典型的操作,如复制、移动、重命名、创建、打开、删除和追加到文件。也可将 File 类用于获取和设置文件属性或有关文件创建、访问及写入操作的 DateTime 信息。

许多 File 方法在您创建或打开文件时返回其他 I/O 类型。可以使用这些其他类型进一步处理文件。有关更多信息,请参见特定的 File 成员,如 OpenTextCreateTextCreate

由于所有的 File 方法都是静态的,所以如果只想执行一个操作,那么使用 File 方法的效率比使用相应的 FileInfo 实例方法可能更高。所有的 File 方法都要求当前所操作的文件的路径是存在的(不包含文件对象)。

File 类的静态方法对所有方法都需要占用一定的cpu处理时间来进行安全检查,即使使用不同的File类的方法重复访问同一个文件时也是如此。

如果打算多次重用某个对象,可考虑改用 FileInfo 的相应实例方法,因为只在创建FileInfo对象时执行一次安全检查。并不总是需要安全检查。

默认情况下,将向所有用户授予对新文件的完全读/写访问权限。

1             string path = @"G:\temp\temp2\myTest.txt";
2             //∴需要先判断路径是否是存在的 不存在则创建
3             string[] strPath=path.Split('\\');
4             string path2= path.Replace("\\" + strPath[strPath.Length - 1], "");
5             if (!Directory.Exists(path2))
6             {
7                 Directory.CreateDirectory(path2);
8             }

 

 1             //第一种写法:基于字符方式的读取
 2             if (!System.IO.File.Exists(path))//∵File.Exists()只是判断文件对象是否存在 而不会去判断你的路径是否是真实的
 3             {
 4                 //Create a file to write to.
 5                 using (StreamWriter sw = System.IO.File.CreateText(path))//Creates or Opens a file for writting UTF-8 Encoded text
 6                 {
 7                     sw.WriteLine("Hello");
 8                     sw.WriteLine("this text file is to use File.Create() method to create.");
 9                     sw.WriteLine("@" + DateTime.Now.ToString("yyyyMMddHHmmsss"));
10                 }
11                 //open the file to read from.
12                 using (StreamReader sr = System.IO.File.OpenText(path))
13                 {
14                     string s = "";
15                     while ((s = sr.ReadLine()) != null)//这个地方判断一定得是null 是""就会发生死循环
16
{ 17 Response.Write(s + "<br>"); 18 } 19 } 20 }

注意:基于字节的方式适用于任何场合,因为任何文件的数据都是基于字节的方式有序存放的。基于字节的方式适用于操作二进制文件,比如exe文件、视频、音频文件等等。其他的文本文件大可选择基于字符的方式操作

 1             //第二种写法:基于字节方式的读取
 2             if (!System.IO.File.Exists(path))
 3             {
 4                 //create the file
 5                 using (FileStream fs = System.IO.File.Create(path)) { }
 6                 //open the stream and write to it
 7                 using (FileStream fs = System.IO.File.OpenWrite(path))
 8                 {
 9                     byte[] info = System.Text.Encoding.UTF8.GetBytes("This is to test the OpenWrite method.");
10                     fs.Write(info, 0, info.Length);
11                 }
12                 //open the stream and read it back.
13                 using (FileStream fs = System.IO.File.OpenRead(path))
14                 {
15                     byte[] info = new byte[(int)fs.Length];
16                     fs.Read(info, 0, info.Length);
17                     Response.Write(System.Text.Encoding.UTF8.GetString(info));
18                 }
19             }
20             //第二种写法 可以使用BinaryWriter 和 BinaryReader 类读取和写入数据,注意这两个类不是用于读取和写入字符串。
21             if(!System.IO.File.Exists(path))
22             {
23             //try
24             //{
25                 FileStream fs = new FileStream(path, FileMode.Create);//CreateNew是创建一个新的,但如果文件已存在则会产生一个错误:IOException||Create等效于 文件存在?覆盖:CreateNew;
26                 BinaryWriter bw = new BinaryWriter(fs);
27                 bw.Write("使用BinaryWriter写入数据" + DateTime.Now.ToString("yyyy/MM/dd HH:mm:sss"));
28                 bw.Close();
29                 fs.Close();
30             //}
31             //catch (Exception ee) 
32             //{
33             //   Response.Write(ee.GetType().Name);
34             //}
35                 fs = new FileStream(path, FileMode.Open, FileAccess.Read);
36                 BinaryReader br = new BinaryReader(fs);
37                 Response.Write(br.ReadString());//读取数据 需要注意
38                 br.Close();
39                 fs.Close();
40             }

FileInfo类:

引用命名空间:using System.IO;

FileInfo 类用于典型的操作,如复制、移动、重命名、创建、打开、删除和追加到文件。

许多 FileInfo 方法在您创建或打开文件时返回其他 I/O 类型。可以使用这些其他类型进一步处理文件。有关更多信息,请参见特定的 FileInfo 成员,如 OpenOpenReadOpenTextCreateTextCreate

如果打算多次重用某个对象,可考虑使用 FileInfo 的实例方法,而不是 File 类的相应静态方法,因为并不总是需要安全检查。

默认情况下,将向所有用户授予对新文件的完全读/写访问权限。

  1         /// <summary>
  2         /// FileInfo类 基于字符的写读文件流
  3         /// </summary>
  4         private void WriteFileInfo()
  5         {
  6             string path1 =Server.MapPath("~/Admin/myDemo/IOFile.txt");
  7             if (path1 != null && path1 != "") 
  8             {
  9                 FileInfo fi = new FileInfo(path1);
 10                 if (!fi.Exists) 
 11                 {
 12                     using (StreamWriter sw = fi.CreateText()) 
 13                     {
 14                         sw.WriteLine("hello");
 15                         sw.WriteLine("and");
 16                         sw.WriteLine("wlecome");
 17                     }
 18                 }
 19                 using (StreamReader sr = fi.OpenText()) 
 20                 {
 21                     string s = "";
 22                     while ((s = sr.ReadLine()) != null) //这个地方判断一定得是null 是“”就会发生死循环
 23                     {
 24                         Response.Write(s + "<br>");
 25                     }
 26                 }
 27                 try
 28                 {
 29                     string path2 = Server.MapPath("~/Admin/myDemo/IOFile1.txt");
 30                     FileInfo fi2 = new FileInfo(path2);
 31                     fi2.Delete();
 32                     fi.CopyTo(path2);
 33                     using (StreamReader sr = fi2.OpenText())
 34                     {
 35                         string s = "";
 36                         while ((s = sr.ReadLine()) != null)
 37                         {
 38                             Response.Write(s + "<br>");
 39                         }
 40                     }
 41                 }
 42                 catch (Exception e) 
 43                 {
 44                     Response.Write(e.ToString());
 45                 }
 46             }
 47         }
 48         /// <summary>
 49         /// 基于字符 写文件流
 50         /// </summary>
 51         private void WriteCharFile()
 52         {
 53             string msg = "adfasdfadfasfafd";
 54             FileStream fs = null;
 55             StreamWriter sw =null;
 56             FileInfo fi = new FileInfo(Server.MapPath("~/Admin/myDemo/IOFile.txt"));
 57             if(!fi.Exists)
 58             {
 59                fs= fi.Create();
 60             }else
 61             {
 62                 fs = fi.OpenWrite();
 63 
 64               
 65             }
 66             sw= new StreamWriter(fs);
 67             sw.Write(msg);
 68             //sw.Flush();//清理当前编写器的所有缓冲区,并使所有缓冲数据写入基础流
 69             sw.Close();
 70             Response.Write("字符 写入流成功");
 71             fs.Close();
 72         }
 73         /// <summary>
 74         /// 基于字符 读文件流
 75         /// </summary>
 76         private void ReadCharFile()
 77         {
 78             string msg = string.Empty;
 79             FileStream fs = null;
 80             FileInfo fi=new FileInfo(Server.MapPath("~/Admin/myDemo/IOFile.txt"));
 81             if (!fi.Exists)
 82             {
 83                 Response.Write("文件对象不存在");
 84             }
 85             else 
 86             {
 87                 fs = fi.OpenRead();
 88                 StreamReader sr = new StreamReader(fs);
 89                 string result = sr.ReadToEnd();
 90                 Response.Write(result);
 91                 sr.Close();
 92                 fs.Close();
 93             }
 94         }
 95         /// <summary>
 96         /// 基于字节 写入文件流
 97         /// </summary>
 98         private void WriteByteFile()
 99         {
100             string msg = "欢迎来到Ivan空间";
101             FileStream fs = null;
102             if (msg != null)
103             {
104                 FileInfo fi = new FileInfo(Server.MapPath("~/Admin/myDemo/IOFile.txt"));
105                 byte[] buffer = System.Text.Encoding.UTF8.GetBytes(msg);
106                 if (!fi.Exists)
107                 {
108                     fs = fi.Create();
109 
110                 }
111                 else
112                 {
113                     fs = fi.OpenWrite();
114                 }
115                 fs.Write(buffer, 0, buffer.Length);
116                 fs.Close();
117                 Response.Write("字节写入流成功<br>");
118             }
119             else 
120             {
121                 Response.Write("字节写入流不成功 原因写入信息为空!<br>");
122             }
123         }
124         /// <summary>
125         /// 基于字节 读文件流
126         /// </summary>
127         private void ReadByteFile()
128         {
129             string msg = string.Empty;
130             FileStream fs = null;
131             byte[] buffer = null;
132             FileInfo fi = new FileInfo(Server.MapPath("~/Admin/myDemo/IOFile.txt"));
133             if (!fi.Exists)
134             {
135                 Response.Write("文件对象不存在<br>");
136             }
137             else 
138             {
139                 fs = fi.OpenRead();
140                 buffer = new byte[(int)fs.Length];
141                  fs.Read(buffer, 0, (int)(fs.Length));
142                  Response.Write(System.Text.Encoding.UTF8.GetString(buffer));
143                  fs.Close();
144             }
145         }

 

转载于:https://www.cnblogs.com/ivan201314/archive/2013/04/23/3036488.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值