您的位置:首页 > 其它

File类与FileInfo类的区别

2013-04-23 13:46 302 查看
这些年代码也写了不少,关于文件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对象时执行一次安全检查。并不总是需要安全检查。

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

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


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


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

//第二种写法:基于字节方式的读取
if (!System.IO.File.Exists(path))
{
//create the file
using (FileStream fs = System.IO.File.Create(path)) { }
//open the stream and write to it
using (FileStream fs = System.IO.File.OpenWrite(path))
{
byte[] info = System.Text.Encoding.UTF8.GetBytes("This is to test the OpenWrite method.");
fs.Write(info, 0, info.Length);
}
//open the stream and read it back.
using (FileStream fs = System.IO.File.OpenRead(path))
{
byte[] info = new byte[(int)fs.Length];
fs.Read(info, 0, info.Length);
Response.Write(System.Text.Encoding.UTF8.GetString(info));
}
}
//第二种写法 可以使用BinaryWriter 和 BinaryReader 类读取和写入数据,注意这两个类不是用于读取和写入字符串。
if(!System.IO.File.Exists(path))
{
//try
//{
FileStream fs = new FileStream(path, FileMode.Create);//CreateNew是创建一个新的,但如果文件已存在则会产生一个错误:IOException||Create等效于 文件存在?覆盖:CreateNew;
BinaryWriter bw = new BinaryWriter(fs);
bw.Write("使用BinaryWriter写入数据" + DateTime.Now.ToString("yyyy/MM/dd HH:mm:sss"));
bw.Close();
fs.Close();
//}
//catch (Exception ee)
//{
//   Response.Write(ee.GetType().Name);
//}
fs = new FileStream(path, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
Response.Write(br.ReadString());//读取数据 需要注意
br.Close();
fs.Close();
}


FileInfo类:

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

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

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

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

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

/// <summary>
/// FileInfo类 基于字符的写读文件流
/// </summary>
private void WriteFileInfo()
{
string path1 =Server.MapPath("~/Admin/myDemo/IOFile.txt");
if (path1 != null && path1 != "")
{
FileInfo fi = new FileInfo(path1);
if (!fi.Exists)
{
using (StreamWriter sw = fi.CreateText())
{
sw.WriteLine("hello");
sw.WriteLine("and");
sw.WriteLine("wlecome");
}
}
using (StreamReader sr = fi.OpenText())
{
string s = "";
while ((s = sr.ReadLine()) != null) //这个地方判断一定得是null 是“”就会发生死循环
{
Response.Write(s + "<br>");
}
}
try
{
string path2 = Server.MapPath("~/Admin/myDemo/IOFile1.txt");
FileInfo fi2 = new FileInfo(path2);
fi2.Delete();
fi.CopyTo(path2);
using (StreamReader sr = fi2.OpenText())
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
Response.Write(s + "<br>");
}
}
}
catch (Exception e)
{
Response.Write(e.ToString());
}
}
}
/// <summary>
/// 基于字符 写文件流
/// </summary>
private void WriteCharFile()
{
string msg = "adfasdfadfasfafd";
FileStream fs = null;
StreamWriter sw =null;
FileInfo fi = new FileInfo(Server.MapPath("~/Admin/myDemo/IOFile.txt"));
if(!fi.Exists)
{
fs= fi.Create();
}else
{
fs = fi.OpenWrite();

}
sw= new StreamWriter(fs);
sw.Write(msg);
//sw.Flush();//清理当前编写器的所有缓冲区,并使所有缓冲数据写入基础流
sw.Close();
Response.Write("字符 写入流成功");
fs.Close();
}
/// <summary>
/// 基于字符 读文件流
/// </summary>
private void ReadCharFile()
{
string msg = string.Empty;
FileStream fs = null;
FileInfo fi=new FileInfo(Server.MapPath("~/Admin/myDemo/IOFile.txt"));
if (!fi.Exists)
{
Response.Write("文件对象不存在");
}
else
{
fs = fi.OpenRead();
StreamReader sr = new StreamReader(fs);
string result = sr.ReadToEnd();
Response.Write(result);
sr.Close();
fs.Close();
}
}
/// <summary>
/// 基于字节 写入文件流
/// </summary>
private void WriteByteFile()
{
string msg = "欢迎来到Ivan空间";
FileStream fs = null;
if (msg != null)
{
FileInfo fi = new FileInfo(Server.MapPath("~/Admin/myDemo/IOFile.txt"));
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(msg);
if (!fi.Exists)
{
fs = fi.Create();

}
else
{
fs = fi.OpenWrite();
}
fs.Write(buffer, 0, buffer.Length);
fs.Close();
Response.Write("字节写入流成功<br>");
}
else
{
Response.Write("字节写入流不成功 原因写入信息为空!<br>");
}
}
/// <summary>
/// 基于字节 读文件流
/// </summary>
private void ReadByteFile()
{
string msg = string.Empty;
FileStream fs = null;
byte[] buffer = null;
FileInfo fi = new FileInfo(Server.MapPath("~/Admin/myDemo/IOFile.txt"));
if (!fi.Exists)
{
Response.Write("文件对象不存在<br>");
}
else
{
fs = fi.OpenRead();
buffer = new byte[(int)fs.Length];
fs.Read(buffer, 0, (int)(fs.Length));
Response.Write(System.Text.Encoding.UTF8.GetString(buffer));
fs.Close();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: