文件的读取:
1.导入命名空间 using System.IO;
2.获取文件流
FileStream fs=new File(path,FileMode.Open);
3.获取读对象
StreamReader sr=new StreamReader(fs);
4.执行读操作 string s =sr.ReadToEnd();
5.关闭读对象 sr.Close();
6.关闭文件流 fs.Close();
二.FileMode的取值有:
Create
创建文件,如果存在就执行覆盖
CreateNew
创建新文件,若存在就会报错
Append
追加,在原来的文件内容之后追加
Open
打开文件,一般是在执行文件读取的时候使用
三.文件的写入:
1.导入命名空间: using System.IO;
2.获取文件流 : FileStream fs=new FileStream(path, FileMode.Create);
3.或者写入的类 StreamWriter sw=new StreamWriter(fs);
4.执行写入的方法
sw.WriteLine(“sdasds”);
5.关闭写入的类 sw.Close();
6.关闭文件流 fs.Close();
四.文件的操作,使用File进行操作
Bool Exists(path)
判断文件是否存在,存在返回true,不存在返回false
Void Copy(string path,string newpath)
将文件复制到一个新的位置
Void Move(string path,string newpath)
将文件移动到一个新的位置,原来的文件不存在
Delete(string path)
删除文件
此处,定义的方法都是静态方法,可以直接使用类名File.方法名去调用。
閱讀更多 低頭搬磚的小強 的文章
關鍵字: FileStream 获取 FileMode