您的位置:首页 > 其它

操作文件 (File和FileInfo类)

2010-12-11 10:49 483 查看

使用File和FileInfo类操作文件

.NET Framework类库包含用于处理文件的两个类似的类:FileInfo和File.

File类为创建、删除和操作文件提供静态方法,而FileInfo类为文件操作提供实例方法。类似与Directory类,File类只提供静态方法,而没有包含任何特性。

view plaincopy to clipboardprint?

using System;

using System.IO;

namespace ConsoleApplicationFile

{

class Program

{

static void Main(string[] args)

{

string filePath = @"D:/temp/textfile.txt";

string fileCopyPath = @"D:/temp/textfile_copy.txt";

string newFileName = @"D:/temp/textfile_newcopy.txt";

try

{

//---if file already existed---

if (File.Exists(filePath))

{

//---delete the file---

File.Delete(filePath);

}

//---create the file again

FileStream fs = File.Create(filePath);

fs.Close();

//---make a copy of the file---

File.Copy(filePath, fileCopyPath);

//---rename the file---

File.Move(fileCopyPath, newFileName);

//---display the creation time---

Console.WriteLine(File.GetCreationTime(newFileName));

//---make the file read-only and hidden---

File.SetAttributes(newFileName, FileAttributes.ReadOnly);

File.SetAttributes(newFileName, FileAttributes.Hidden);

}

catch (IOException ex)

{

Console.WriteLine(ex.Message);

}

catch (Exception ex)

{

Console.WriteLine(ex.Message);

}

Console.ReadLine();

}

}

}

File类包含用于将内容写入文件的4种方法:

WriteAllText():创建文本,将字符串写入该文件,关闭文件

AppendAllText():将字符串附加到已有的文件

WriteAllLines():创建文件,将字符串数组写入该文件,关闭文件

WriteAllBytes():创建文件,将字节数组写入该文件,关闭文件

下面的代码显示了如何使用各种方法将一些内容写入文件:

view plaincopy to clipboardprint?

using System;

using System.IO;

using System.Text;

namespace ConsoleApplicationFile

{

class Program

{

static void Main(string[] args)

{

string filePath = @"D:/temp/textfile.txt";

string strTextToWrite = "This is a string";

string[] strLinesToWrite = new string[] { "Line1","Line2"};

byte[] bytesToWrite = ASCIIEncoding.ASCII.GetBytes("This is a string");

try

{

File.WriteAllText(filePath, strTextToWrite);

File.AppendAllText(filePath, strTextToWrite);

File.WriteAllLines(filePath, strLinesToWrite);

File.WriteAllBytes(filePath, bytesToWrite);

}

catch (IOException ex)

{

Console.WriteLine(ex.Message);

}

catch (Exception ex)

{

Console.WriteLine(ex.Message);

}

Console.ReadLine();

}

}

}

File类也包含用于从文件读取内容的3种方法:

ReadAllText():打开文件,读取该文件中的所有文本并放入字符串中,关闭文件

ReadAllLines():打开文件,读取该文件中的所有文本并放入字符串数组中,关闭文件

ReadAllBytes():打开文件,读取该文件中的所有文本并放入字节数组中,关闭文件
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: