当前位置: 移动技术网 > IT编程>开发语言>c# > C#的FileInfo类实现文件操作实例

C#的FileInfo类实现文件操作实例

2019年07月18日  | 移动技术网IT编程  | 我要评论
c#的fileinfo类提供了与file类相同的功能,不同的是fileinfo提供的都是成员方法,使用示例如下所示: 1、读文件: //创建只读 system.

c#的fileinfo类提供了与file类相同的功能,不同的是fileinfo提供的都是成员方法,使用示例如下所示:

1、读文件:

//创建只读 system.io.filestream。 
public system.io.filestream openread() 
//创建使用 utf8 编码、从现有文本文件中进行读取的 system.io.streamreader。
public system.io.streamreader opentext()

2、写文件:

//创建只写 system.io.filestream。 
public system.io.filestream openwrite()

3、追加内容:

//创建一个 system.io.streamwriter,它向 system.io.fileinfo 的此实例表示的文件追加文本。 
public system.io.streamwriter appendtext()

4、打开文件:

//在指定的模式中打开文件。 
public system.io.filestream open(system.io.filemode mode) 
//用读、写或读/写访问权限在指定模式下打开文件。 
public system.io.filestream open(system.io.filemode mode, system.io.fileaccess access) 
//用读、写或读/写访问权限和指定的共享选项在指定的模式中打开文件。
 public system.io.filestream open(system.io.filemode mode, system.io.fileaccess access, system.io.fileshare share)

5、复制、移动、替换:

//将现有文件复制到新文件,不允许覆盖现有文件。 
public system.io.fileinfo copyto(string destfilename) 
//将现有文件复制到新文件,允许覆盖现有文件。 
public system.io.fileinfo copyto(string destfilename, bool overwrite) 
//将指定文件移到新位置,并提供指定新文件名的选项。 
public void moveto(string destfilename) 
//使用当前 system.io.fileinfo 对象所描述的文件替换指定文件的内容,这一过程将删除原始文件,并创建被替换文件的备份。 
public system.io.fileinfo replace(string destinationfilename, string destinationbackupfilename) 
//使用当前 system.io.fileinfo 对象所描述的文件替换指定文件的内容,这一过程将删除原始文件,并创建被替换文件的备份。还指定是否忽略合并错误。 
public system.io.fileinfo replace(string destinationfilename, string destinationbackupfilename, bool ignoremetadataerrors)

6、加密解密、删除:

//将某个文件加密,使得只有加密该文件的帐户才能将其解密。 
public void encrypt() 
//解密由当前帐户使用 system.io.fileinfo.encrypt() 方法加密的文件。
 public void decrypt() 
//永久删除文件。 
public override void delete()

7、获得文件属性:

//获取父目录的实例。 
public system.io.directoryinfo directory { get; } 
//获取表示目录的完整路径的字符串。 
public string directoryname { get; } 
//获取指示文件是否存在的值。 
public override bool exists { get; } 
//获取或设置确定当前文件是否为只读的值。 
public bool isreadonly { set; get; } 
//获取当前文件的大小(字节)。 
public long length { get; } 
//获取文件名。 
public override string name { get; }

在fileinfo中获取文件的相关属性不再是方法了,都是通过属性获得的,并且除是否只读属性为可读可写的,其他属性都是只读的。

总结:

大家注意到,我们在fileinfo中提供的方法不再是静态的,并且返回值都是filestream类型的,是一个文件流,因此我们在使用fileinfo这个类时还需要结合filestream类一起使用。而在介绍file类时,所有的操作都是通过静态方法实现的,并且返回值都是具体的值类型
这也算是对file类与fileinfo类的粗略的对比。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网