1 文件创建
1.1通过Create()方法创建非UTF-8编码文件
public static FileStream Create(string path,int bufferSize,FileOptions options)
path:要创建的文件路径及名称
bufferSize:用于读取和写入文件的已放入缓冲区的字节数
options:FileOptions值之一,描述如何创建或覆盖该文件。
返回值:FileStream对象。
例1:纯文本格式文本文件创建 同名则覆盖
FileStream fs = File.Create("D:\\test.txt");
例2:创建指定缓冲区大小的文件
string path = "D:\\test.txt";
using (FileStream fs = File.Create(path, 1024))
{
Byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");
fs.Write(info, 0, info.Length);
}
例3:创建可一步读取和写入的文本文件
File.Create( "D:\\test.txt",1024,FileOptions.Asynchronous);
1.2通过CreateText()方法创建UTF-8编码文件
public static StreamWriter Create(string path);
path:要创建的文件路径及名称
返回值:Stream Writer对象,它使用UTF-8编码写入制定的文件。
例1:创建XML文件,并向其中写入文本。
string path = @"D:\MyTest.xml";
using(StreamWriter sw=File.CreateText(path))
{
sw.WriteLine("<TextBlock>");
sw.WriteLine("<TextBlock>");
sw.WriteLine("<TextBlock>");
sw.WriteLine("</TextBlock>");
}
例2:创建一个位图文件
string path = @"D:MyTe
File.CreateText(path);
1.3 FileInfo创建文件
FileInfo fileInfo = new FileInfo("FileInfoMethord.txt");//示例化FileInfo类
StreamWriter sw = fileInfo.CreateText();//创建文件
sw.Write("This is FileInfo Methord.");//向文件中写入信息
sw.Close();//释放资源
2 文件打开
2.1 以读/写方式打开文件
File.Open(path, FileMode.Open);
File.Open(path, FileMode.OpenOrCreate);
File.Open(path, FileMode.Truncate);
File.Open(path, FileMode.Append);