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);
}
}
}
本文链接:https://my.lmcjl.com/post/1394.html
4 评论