对文件进行操作(只操作小文件)
bool Exists(string path) 判断文件是否存在
FileStream Create(string path) 创建文件
void Move(string sourcePath,string destPath) 剪切文件
void Copy(string sourcePath,string destPath) 复制文件(destPath不能是目录或现有文件)
if (!File.Exists(@"D:\Users\Desktop\Study.txt")) { File.Create(@"D:\Users\Desktop\Study.txt"); } File.Move(@"D:\Users\Desktop\Study.txt", @"D:\StudyUp.txt"); File.Copy(@"D:\StudyUp.txt", @"D:\Users\Desktop\StudyTwo.txt"); File.Delete(@"D:\StudyUp.txt"); File.Delete(@"D:\Users\Desktop\StudyTwo.txt");
读
string[] ReadAllLines() 逐行读取文本
//ReadAllLines()默认采用的编码格式是utf-8 string[] str=File.ReadAllLines(@"D:\Users\desktop\Study.txt",Encoding,Default);
string ReadAllText() 读取文本
//ReadAllText()默认采用的编码格式是utf-8
string str=File.ReadAllText(@"D:\Users\desktop\Study.txt");
byte[] ReadAllBytes() 读取文本
byte[] buffer=File.ReadAllBytes(@"D:Users\desktop\Study.txt"); //字节数组--->字符串 string str = Encoding.UTF-8.GetString(buffer); //如果转成gbk string strGBK = Encoding.GetEncoding("gbk").GetString(buffer);
写
void WriteAllBytes() 以字节写入文本
string num="一二三四五六七八九十"; //字符串--->字节数组 byte[] buffer=Encoding.Default.GetBytes(num); File.WriteAllBytes(@"D:\Users\desktop\Study.txt",buffer);
void WriteAllLines() 以行的形式写入文本
File.WriteAllLines(@"D:\Users\desktop\Study.txt",new string[]{"男","女"});
void WriteAllText() 以字符串的形式写入文本
File.WriteAllText(@"D:\Users\desktop\Study.txt","乱七八糟");