读写文本文件
通过文件流
步骤:
1. 创建一个文件流
2. 创建相应的读写器
3. 执行读写操作
4. 关闭读写器
5. 关闭文件流 必须关闭,否则下次不能使用
* 引入命名空间
System.IO;
* 文件流 FileStream myfs = new FileStream( 文件路径, FileMode枚举类型选择方式,……);
* 读写器
StreamReader mySr = new StreamReader(fs); //读
StreamWriter sw = new StreamWriter(fs);//写
示例:
//文件读写
//写
string path="a.txt";
using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write))
{
StreamWriter sw = new StreamWriter(fs);
sw.Write("这是一个写入文件的测试!");
sw.Close();
}
//读
using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
{
StreamReader sr = new StreamReader(fs);
Console.WriteLine(sr.ReadToEnd());
sr.Close();
}
string path1 = @"C:\Users\dell\Desktop\01.txt";
if (File.Exists(path1))//文件存在则读取
{
Console.WriteLine("下面是从{0}读取到的文件:",path1);
string[] strall = File.ReadAllLines(path1);
foreach(string s in strall )
{
Console.WriteLine(s);
}
}
else //不存在则新建并写入
{
string[] strNew = { "写入","这些信息","来","检查"};
File.WriteAllLines(path1, strNew);
Console.WriteLine("文件已经写入");
}
文本文件可以不通过文件流读写
StreamWriter允许直接将字符串写入文件
StreamWriter mySw = new StreamWriter(path);
mySw.Write(content);
mySw.Close();
StreamReader允许直接读取文件内容
StreamReader mySr = new StreamReader(path);
content = mySr.ReadToEnd();
txtContent.Text = content;
mySr.Close();
File类 文件操作
文件操作还包括拷贝、移动、删除等等,.NET提供一个File类,提供各种操作文件方法
* Exists(string path)
用于检查指定文件是否存在,该方法返回一个布尔值
* Copy(string SourceFilePath,string DestinationFilePath
按指定路径的源文件中的内容复制到目标文件中,如果目标文件不存在,则在指定路径中新建一个文件
* Move (string sourceFileName,string destFileName)
将指定文件移动到一个新的路径
* Delete(string path)
删除指定的文件,如果指定的文件不存在,则不引发异常
File类读写文件示例
string path = @"d:\test.txt";
if (File.Exists(path)) //如果文件存在,则读取文件内容
{
//读取文件
string[] content=File.ReadAllLines(path);
Console.WriteLine("读取文件:");
foreach (string s in content)
{
Console.WriteLine(s);
}
}
Else //如果文件不存在,则新建文件并写入内容
{
//写入文件
string[] content = {"Hello","And","Welcom"};
File.WriteAllLines(path,content);
Console.WriteLine("文件已写入!");
}
Directory类 目录操作
- Exists(string path)
用于检查指定文件夹在磁盘上是否存在 - Move(string sourceDirName, string destDirName)
用于将文件或目录及其内容移到新位置 - Delete(string,Boolean)
删除指定目录,如果bool指定true,则删除子目录中的所有目录内容 - Delete(string path)
删除指定的文件,如果指定的文件不存在,则不引发异常
静态类和非静态类
public static class Directory
public static class File
对于Directary和File类的系统定义都有static关键字,是静态类。
静态类:
- 只包含静态成员,不能包含非静态成员
- 不能被实例化
- 不能包含实例构造函数
访问修饰符
成员访问权限
- public 访问不受限制
- internal 访问范围仅限于同一程序集
- protected 本类和其子类中可以访问
- protected internal 在同一程序集中可以访问,不同程序集中的子类可以访问
- private 仅在本类中可以访问默认值
类的访问权限:
- public 访问不受限制
- sealed 密封类 不允许从他这儿继承
- internal 访问范围仅限于同一程序集