> 文章列表 > C# 文件操作

C# 文件操作

C# 文件操作

一 File\\FileInfo类

在.NETFramework提供的文件操作类基本上都位于System.IO的命名空间下。操作硬盘文件常用的有两个类File\\FileInfo.

File类主要是通过静态方法实现的,FileInfo类是通过实例方法。

File类核心成员

 FileInfo类的实例成员提供了与File相似的功能,方法名称基本一致,大多数情况下,FileInfo和File类可以互换使用,但是由于File类所提供的方法都是静态方法,所以如果只想执行一个操作,使用File类的效率相对更高一点。

using System;
using System.IO;namespace 文件操作01
{class Program{static void Main(string[] args){FileStream fs = null;StreamWriter sw = null;string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\\\" + "123.txt";if (!File.Exists(path)){fs = File.Create(path);Console.WriteLine("新建一个文件:{0}", path);}else{fs = File.Open(path, FileMode.Open);Console.WriteLine("文件已经存在,直接打开", path);}sw = new StreamWriter(fs);sw.WriteLine("测试文本");Console.WriteLine("向文件写入文本数据");sw.Flush();sw.Close();fs.Close();Console.WriteLine("关闭数据流");Console.ReadKey();}}
}

二 Directory/DirectoryInfo类

这两个类中都包含了一组用来创建、移动删除、和枚举所有目录或者子目录的成员。

Directory常用成员:

 DirectoryInfo类所提供的成员与Directory类的相似,在大多数情况下,可以互换使用。

using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Threading.Tasks;namespace 文件操作02
{class Program{static void Main(string[] args){string dirPath = "C:\\\\存储盘";string filePath = string.Format("{0}\\\\{1}", dirPath, "wuzhTest.txt");if (!Directory.Exists(dirPath)){Directory.CreateDirectory(dirPath);Console.WriteLine("新建一个目录:{0}", dirPath);}else{Console.WriteLine("目录已经存在");}FileInfo file = new FileInfo(filePath);if (!file.Exists){file.Create();Console.WriteLine("新建一个文件:{0}", filePath);}else{             Console.WriteLine("文件{0}已经存在", filePath);}}}
}

三 流(Stream)

流(Stream)可以理解为内存中的字节序列,Stream类是所有流的抽象基类,每个具体的存储实体都可以通过Stream派生类来实现,比如FileStream类。

流涉及到三个基本操作:

1 对流进行读取,

2 对流进行写入

3 对流进行查找

Stream类常用成员如下:

 

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;namespace 文件操作03
{class Program{static void Main(string[] args){string filePath = "C:\\\\存储盘\\\\wuzh04.txt";using(FileStream fs = File.Open(filePath, FileMode.OpenOrCreate)){string msg = " hello SMS";StreamWriter sw = new StreamWriter(fs);//创建StreamWriter对象Console.WriteLine("开始写入{0}到文件",msg);sw.Write(msg);StreamReader sr = new StreamReader(fs);//创建StreamReader对象Console.WriteLine("写入文件中的数据为:\\n{0}", sr.ReadToEnd());sw.Close();sr.Close();Console.Read();}}}
}

读写器

文本读写器:TextReader类,TextWriter类

字符串读写器:StringReader类,StringWriter类

二进制读写器:BinaryReader类,BinaryWriter类

流读写器:StreamReader类,StreamWriter类

四 文件异步操作

以FIleStream为例