C#提供了一次性读写所有数据和按照数据流的方式进行读写,这篇文章总结一下一次行读取的方式——File类
——File类
前面说过创建文件夹的方式,那么有什么方式可以往文件夹中添加文件呢,那就是File类了,File类是一个静态类,下面就总结几个常用的方法
——文件操作
创建文件,参数为路径和文件名字的字符串
File.Create(@"C:\Users\Blue\Desktop\new.txt");
删除文件,参数为路径和文件名字的字符串
File.Delete(@"C:\Users\Blue\Desktop\new.txt");
拷贝,将第一个拷贝到第二个中,第二参数文件为新创建的
File.Copy(@"C:\Users\Blue\Desktop\daysInMonth.html", @"C:\Users\Blue\Desktop\new1.txt")
剪切,和文件夹的剪切方式一样
File.Move(@"C:\Users\Blue\Desktop\daysInMonth.html", @"C:\Users\Blue\Desktop\move.html")
——读写数据
先说一下读取数据,三种常用的方式
- ReadAllBytes( ),以字节的形式读取数组,返回字节数组
- ReadAllLines(),以行的方式读取文件,返回字符串数组
- ReadAllText(),读取文档中所有的数据,返回字符串
ReadAllBytes( )的例子
/*
这里我读取了一个html文件,并打印到控制台
ReadAllBytes()返回的是一个byte类型的数组(字节数组)
Encoding.Default.GetString(buffer)用这个方法将字节数组转换成字符串
*/
string path = @"C:\Users\Blue\Desktop\daysInMonth.html";
byte[] buffer = File.ReadAllBytes(path);
string result = Encoding.Default.GetString(buffer);
Console.WriteLine(result);
ReadAllLines()的例子
//文本文件中的数据是一行一行的,像下面这样
/*
hello
world
C#
*/
string path = @"C:\Users\Blue\Desktop\test.txt";
string[] result = File.ReadAllLines(path,Encoding.Default);
foreach (string item in result)
{
Console.WriteLine(item);
}
//打印出来就像下面这样
/*
hello
world
C#
*/
ReadAllText()的例子
//当时文本文件的时候,这个都出来跟字节数组的方式是一样的
string path = @"C:\Users\Blue\Desktop\daysInMonth.html";
string result = File.ReadAllText(path,Encoding.Default);
Console.WriteLine(result);
往文件中写入数据的常用方式,这里的三种方式跟上面的读取时对应的
- WriteAllBytes(文件路径,字节数组 ),以字节数组的方式写入
- WriteAllLines(路径,字符串数组,[编码方式]),把数组中的每个元素按行写入
- WriteAllText(路径,字符串,[编码方式])
WriteAllBytes()的例子
/*
这里就一个注意的,记得把字符串转换成字节数组
*/
string str="hello world";
byte[] buffer = Encoding.Default.GetBytes(str);
string path = @"C:\Users\Blue\Desktop\new.txt";
File.WriteAllBytes(path, buffer);
WriteAllLines( )的例子
/*
写成的文档就是hello一行,world一行
*/
string[] str=new string[]{"hello","world"};
string path = @"C:\Users\Blue\Desktop\new.txt";
File.WriteAllLines(path,str,Encoding.Default);
WriteAllText( )的例子
/*
同样对于文本文件,字节数组方式写入和这个方式写入是一样的
但是对于像图片之类的,就只能用字节数组方式写入了
*/
string str="hello world";
string path = @"C:\Users\Blue\Desktop\new.txt";
File.WriteAllText(path,str,Encoding.Default);
注意:上面三种写入的方式,都会把文件中原原来的数据替换掉,相当于我原来写的就没有了,那如果我要往后面添加数据,我还得先读出来,再往上面拼接,再写入,好像很麻烦,下面有方法可以解决
把上面写入数据方法的Write改为Append就行了,比如说这样
string str="I am Appended";
string path = @"C:\Users\Blue\Desktop\new.txt";
File.AppendAllText(path,str,Encoding.Default);
/*
这样就往文件中添加了数据
*/
以上的写入数据方式中,如果路径目标存在,则路径目标会被覆盖,如果路径目标不存在,则会被创建对应的文件!