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


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类的粗略的对比。


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3