C#文件操作
File类
1.方法
(1)判存 File.Exist();
(2)复制 File.Copy();
(3)剪切 File.Move();
(4)删除 File.Delete();
2.文件读写
(1)字节读取
byte[] buffer = File.ReadAllByte(string path);
//将buffer以系统默认的编码格式转换成字符串
string text = System.Text.Encoding.Default.GetString(buffer);
(2)每行读取
string[] text = File.ReadAllLines(string path , Encoding.Default);
然后遍历输出。
(3)全部读取
string text = File.ReadAllText(string path , Encoding.Default);
(4)字节写入
byte[] buffer = System.Text.Encoding.Default.GetByte(text);
File.WriteAllBytes(string path , buffer);
(5)每行写入
string[] text = {" xxx " ," xxx ", " xxx ", " xxx "};
File.WriteAllLines(string path , text );
(6)全部写入
string text = “xxxxxxxxxxxxxxxxxxxx”;
File.WriteAllText(string path , text );
(7)追加写入
string text = “xxxxxxxxxxxxxxxxxxxx”;
File.AppendAllText(string path , text );
Directory类
1.常用方法
(1)从指定路径创建目录
CreateDirectory(String path);
(2)从指定路径删除空目录。
Delete(String path) ;
(3)删除指定的目录,并删除该目录中的所有子目录和文件
Delete(String, true)
(4)返回指定目录中文件的名称(包括其路径)。
GetFiles(String);
(5)将文件或目录及其内容移到新位置(剪切)。
Move(String path, String NewPath);
FileStream类
1. 常用方法
(1)读
using (FileStream fs = new FileStream(@“path”, FileMode.Open, FileAccess.Read))
{
byte[] buffer = new byte[fs.Length];
int r = fs.Read(buffer, 0, buffer.Length);
string text = System.Text.Encoding.Default.GetString(buffer);
}
(2)写
using (FileStream fs = new FileStream(@“path”, FileMode.OpenOrCreate, FileAccess.Write))
{
string text = “写入内容”;
byte[] buffer = System.Text.Encoding.Default.GetBytes(text);
fs.Write(buffer,0,buffer.Length);
}
(3)文件复制
private void FileCopy(string SourcePath,string TargetPath)
{
using (FileStream fsRead = new FileStream(SourcePath,FileMode.Open,FileAccess.Read))
{using (FileStream fsWrite = new FileStream(TargetPath,FileMode.OpenOrCreate,FileAccess.Write))
{
byte[] buffer = new byte[1024 * 1024 * 2];
while (true)
{
int r = fsRead.Read(buffer, 0, buffer.Length);
if (r==0)
{
break;
}
fsWrite.Write(buffer, 0, r);
}
}
}
}
StreamReader类 和 StreamWriter类
1. 读
(1)方法一
using (FileStream fsRead = new FileStream(@“C:\Users\suppo\Desktop\HTTP.txt”, FileMode.Open, FileAccess.Read))
{
using (StreamReader sr = new StreamReader(fsRead))
{
while (!sr.EndOfStream)
{
text += sr.ReadLine() + “\r\n”;
textBox1.Text = text;
}
}
}
(2)方法二
using (StreamReader sr = new StreamReader(@“C:\Users\suppo\Desktop\HTTP.txt”))
{
while (!sr.EndOfStream)
{
text += sr.ReadLine() + “\r\n”;
textBox1.Text = text;
}
}
2. 写
(1)方法一
//FileMode.Append 追加写入 FileMode.Open覆盖写入
using (FileStream fsWrite = new FileStream(@“C:\Users\suppo\Desktop\HTTP.txt”, FileMode.Open, FileAccess.Write))
{
using (StreamWriter sr = new StreamWriter(fsWrite))
{
sr.WriteLine(text);
}
}
(2)方法2
//第二个参数为false是覆盖写入,为true是追加写入
using (StreamWriter sr = new StreamWriter(@“C:\Users\suppo\Desktop\HTTP.txt”,true))
{
sr.WriteLine(text);
}
注意:
File是操作小文件的。
FileStream 是操作字节的。大文件小文件都可以操作。
StreamReader类 和 StreamWriter类是操作大文件的。