C#-File类

File类

File.Exists(String) 的方法介绍

1)作用:确定指定的文件是否存在。
2)语法:

public static bool Exists (string path);

File.Create("path");

File.Create("path");

 File.Open 的方法介绍

1)作用:打开指定路径上的 FileStream。
2)语法:

public static System.IO.FileStream Open (string path, System.IO.FileMode mode);
public static System.IO.FileStream Open (string path, System.IO.FileMode mode, System.IO.FileAccess access);
public static System.IO.FileStream Open (string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.

 File.OpenRead(String) 的方法介绍

1)作用:打开现有文件以进行读取。
2)语法:返回FileStream是指定路径上的只读 FileStream。

public static System.IO.FileStream OpenRead (string path);

9: File.OpenText(String) 的方法介绍

1)作用:打开现有 UTF-8 编码文本的文件,以进行读取。
2)语法:返回StreamReader是指定路径上的 StreamReader。

public static System.IO.StreamReader OpenText (string path);

FileInfo类

FileInfo的Exsts的使用

FileInfo info=new FileInfo("path");
info.Exists

FileInfo的Create的使用

FileInfo info=new FileInfo("path");
info.Create();

其实File类和FileInfo类大致相同,File类主要使用调用静态方法将内部的进行调用,且每次方法的调用都伴随着路径的填写。但是FileInfo对方法的调用是使用对象作为媒介,FileInfo的一个对象仅仅针对一个路径,File和FileInfo的方法大致相同。

StreamReader类

StreamReader类是用于读取文本文件的类。

 

属性:

BaseStream:返回基础流

CurrentEncoding:获取当前StreamReader对象正在使用的当前字符编码

EndOfStream获取一个值,该值表示当前的流位置是否在流的末尾

主要方法:

简单实例:

实例一:

 //StreamReader 简单读取
StreamReader reader = new StreamReader(@"D:\test.txt",Encoding.Default);//初始化读取 设置编码格式,否则中文会乱码
string readStr = reader.ReadLine();//从流中读取一行  reader.ReadToEnd()读取全部
reader.Close();//关闭流

 实例二:

//逐行读取文件处理至文件结束
 StreamReader reader = new StreamReader(filename);
 string str = String.Empty;
 while ((str=reader.ReadLine() )!= null)
 {
      tbx_content.Text = tbx_content.Text+ str + '\n';
 }

备注一:路径path的写法,路径中的‘\’是转义字符,所以写成字符串的话要变成'\\'。例如:“C:\\Windows\\Work”

而对于多级目录的话会有很多的‘\\’是不方便的,所以C#中可以用  @"C:\Windows\Work"进行多级转义。

备注二:读取中文文件显示乱码的原因是 文件的编码格式与读取流的编码格式不一致导致的。

具体来说,

a.使用File和FileInfo创建文本文件使用的默认编码格式使UTF-8

b.在windows环境下手工创建的文件是ANSI格式。

c.StreamReader不指定编码格式的话,使用Unicode

所以我们对于读取中文文本时要使用StreamReader sr=new StreamReader(filename,Encoding.Default);使编码格式统一。。
原文链接:https://blog.csdn.net/lsxa123/article/details/88963410

猜你喜欢

转载自blog.csdn.net/qq_42705793/article/details/127772768