您的位置:首页 > 其它

File和FileInfo的区别总结

2011-04-08 22:28 501 查看
File类提供了创建、删除、复制、移动文件的静态方法

FileInfo类提供了创建、删除、复制、移动文件的实例方法。(不可继承)

File类的方法每次执行都要验证安全机制,所以在少量使用的时候用File效率高,但是如果用的多了 要用FileInfo效率高

string path = @"D:/test.txt";
if (!File.Exists(path))
{

using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("Hello");
sw.WriteLine("World");
}
using (StreamReader sr = File.OpenText(path))
{
StringBuilder sb = new StringBuilder();
string str = "";
while ((str = sr.ReadLine()) != null)
{
sb.Append(str);
}
}
try
{
string path2 = @"D:/temp.txt";
string pathNew = @"D:/tempNew.txt";
File.Delete(path2);
File.Copy(path2, pathNew);
File.Delete(pathNew);
}
catch (IOException ex)
{
}
}
string path3 = @"D:/net.txt";
if (File.Exists(path3))
{
File.Delete(path);
}
using (FileStream fs = File.Create(path3))
{
byte[] byteData = new UTF8Encoding(true).GetBytes("this is some text in the text");
fs.Write(byteData, 0, byteData.Length);
}
using (StreamReader sr = File.OpenText(path3))
{
StringBuilder sb = new StringBuilder();
string str = "";
while ((str = sr.ReadLine()) != null)
{
sb.Append(str);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: