FileInfo 类

定义

提供用于创建、复制、删除、移动和打开文件的属性和实例方法,并且帮助创建 FileStream 对象。 此类不能被继承。

public ref class FileInfo sealed : System::IO::FileSystemInfo
public sealed class FileInfo : System.IO.FileSystemInfo
[System.Serializable]
public sealed class FileInfo : System.IO.FileSystemInfo
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class FileInfo : System.IO.FileSystemInfo
type FileInfo = class
    inherit FileSystemInfo
[<System.Serializable>]
type FileInfo = class
    inherit FileSystemInfo
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type FileInfo = class
    inherit FileSystemInfo
Public NotInheritable Class FileInfo
Inherits FileSystemInfo
继承
继承
属性

示例

以下示例演示 类的一些main成员FileInfo

首次检索属性时, FileInfo 调用 Refresh 方法并缓存有关文件的信息。 在后续调用中,必须调用 Refresh 以获取信息的最新副本。

using namespace System;
using namespace System::IO;

int main()
{
   String^ path = Path::GetTempFileName();
   FileInfo^ fi1 = gcnew FileInfo( path );
   //Create a file to write to.
   StreamWriter^ sw = fi1->CreateText();
   try
   {
     sw->WriteLine( "Hello" );
     sw->WriteLine( "And" );
     sw->WriteLine( "Welcome" );
   }
   finally
   {
     if ( sw )
        delete (IDisposable^)sw;
   }

   //Open the file to read from.
   StreamReader^ sr = fi1->OpenText();
   try
   {
      String^ s = "";
      while ( s = sr->ReadLine() )
      {
         Console::WriteLine( s );
      }
   }
   finally
   {
      if ( sr )
         delete (IDisposable^)sr;
   }

   try
   {
      String^ path2 = Path::GetTempFileName();
      FileInfo^ fi2 = gcnew FileInfo( path2 );

      //Ensure that the target does not exist.
      fi2->Delete();

      //Copy the file.
      fi1->CopyTo( path2 );
      Console::WriteLine( "{0} was copied to {1}.", path, path2 );

      //Delete the newly created file.
      fi2->Delete();
      Console::WriteLine( "{0} was successfully deleted.", path2 );
   }
   catch ( Exception^ e )
   {
      Console::WriteLine( "The process failed: {0}", e );
   }
}
using System;
using System.IO;

class Test
{
    
    public static void Main()
    {
        string path = Path.GetTempFileName();
        var fi1 = new FileInfo(path);

        // Create a file to write to.
        using (StreamWriter sw = fi1.CreateText())
        {
            sw.WriteLine("Hello");
            sw.WriteLine("And");
            sw.WriteLine("Welcome");
        }	

        // Open the file to read from.
        using (StreamReader sr = fi1.OpenText())
        {
            var s = "";
            while ((s = sr.ReadLine()) != null)
            {
                Console.WriteLine(s);
            }
        }

        try
        {
            string path2 = Path.GetTempFileName();
            var fi2 = new FileInfo(path2);

            // Ensure that the target does not exist.
            fi2.Delete();

            // Copy the file.
            fi1.CopyTo(path2);
            Console.WriteLine($"{path} was copied to {path2}.");

            // Delete the newly created file.
            fi2.Delete();
            Console.WriteLine($"{path2} was successfully deleted.");
        }
        catch (Exception e)
        {
            Console.WriteLine($"The process failed: {e.ToString()}");
        }
    }
}
Imports System.IO

Public Class Test

    Public Shared Sub Main()
        Dim path1 As String = Path.GetTempFileName()
        Dim path2 As String = Path.GetTempFileName()
        Dim fi As New FileInfo(path1)

        ' Create a file to write to.
        Using sw As StreamWriter = fi.CreateText()
            sw.WriteLine("Hello")
            sw.WriteLine("And")
            sw.WriteLine("Welcome")
        End Using

        Try
            ' Open the file to read from.
            Using sr As StreamReader = fi.OpenText()
                Do While sr.Peek() >= 0
                    Console.WriteLine(sr.ReadLine())
                Loop
            End Using

            Dim fi2 As New FileInfo(path2)

            ' Ensure that the target does not exist.
            fi2.Delete()

            ' Copy the file.
            fi.CopyTo(path2)
            Console.WriteLine($"{path1} was copied to {path2}.")

            ' Delete the newly created file.
            fi2.Delete()
            Console.WriteLine($"{path2} was successfully deleted.")

        Catch e As Exception
            Console.WriteLine($"The process failed: {e.ToString()}.")
        End Try
    End Sub
End Class

此示例生成类似于以下内容的输出。

Hello
And
Welcome
C:\Users\userName\AppData\Local\Temp\tmp70AB.tmp was copied to C:\Users\userName\AppData\Local\Temp\tmp70CB.tmp.
C:\Users\userName\AppData\Local\Temp\tmp70CB.tmp was successfully deleted.

注解

FileInfo将 类用于典型的操作,例如复制、移动、重命名、创建、打开、删除和追加到文件。

如果对同一个文件执行多个操作,则使用FileInfo实例方法而不是类的相应静态方法File可能更有效,因为并不总是需要安全检查。

创建或打开文件时, FileInfo 许多方法返回其他 I/O 类型。 可以使用这些其他类型进一步操作文件。 有关详细信息,请参阅特定FileInfo成员,例如 Open、、OpenReadOpenTextCreateTextCreate

默认情况下,向所有用户授予对新文件的完整读/写访问权限。

下表描述了用于自定义各种 FileInfo 方法行为的枚举。

枚举 描述
FileAccess 指定对文件的读取和写入访问权限。
FileShare 指定已使用的文件允许的访问级别。
FileMode 指定是保留还是覆盖现有文件的内容,以及创建现有文件的请求是否会导致异常。

注意

在接受路径作为输入字符串的成员中,该路径的格式必须正常,否则将引发异常。 例如,如果路径是完全限定的,但以空格开头,则不会在 类的方法中剪裁该路径。 因此,路径格式不正确,并引发异常。 同样,路径或路径组合不能完全限定两次。 例如,“c:\temp c:\windows”在大多数情况下也会引发异常。 使用接受路径字符串的方法时,请确保路径格式良好。

在接受路径的成员中,路径可以引用文件或仅引用目录。 指定的路径还可以引用服务器和共享名称的相对路径或通用命名约定 (UNC) 路径。 例如,以下所有路径都是可接受的路径:

  • C# 中的“c:\\MyDir\\MyFile.txt”或 Visual Basic 中的“c:\MyDir\MyFile.txt”。

  • C# 中的“c:\\MyDir”或 Visual Basic 中的“c:\MyDir”。

  • C# 中的“MyDir\\MySubdir”或 Visual Basic 中的“MyDir\MySubDir”。

  • C# 中的“\\MyServer\\MyShare”或 Visual Basic 中的“\\MyServer\MyShare”。

FileInfo 提供以下属性,使你能够检索有关文件的信息。 有关如何使用每个属性的示例,请参阅属性页。

  • 属性 Directory 检索表示文件的父目录的 对象。

  • 属性 DirectoryName 检索文件的父目录的完整路径。

  • 属性 Exists 先检查文件是否存在,然后再对其进行操作。

  • 属性 IsReadOnly 检索或设置一个值,该值指定是否可以修改文件。

  • 检索 Length 文件的大小。

  • 检索 Name 文件的名称。

构造函数

FileInfo(String)

初始化作为文件路径的包装的 FileInfo 类的新实例。

字段

FullPath

表示目录或文件的完全限定目录。

(继承自 FileSystemInfo)
OriginalPath

最初由用户指定的目录(不论是相对目录还是绝对目录)。

(继承自 FileSystemInfo)

属性

Attributes

获取或设置当前文件或目录的特性。

(继承自 FileSystemInfo)
CreationTime

获取或设置当前文件或目录的创建时间。

(继承自 FileSystemInfo)
CreationTimeUtc

获取或设置当前文件或目录的创建时间,其格式为协调世界时 (UTC)。

(继承自 FileSystemInfo)
Directory

获取父目录的实例。

DirectoryName

获取表示目录的完整路径的字符串。

Exists

获取指示文件是否存在的值。

Extension

获取文件名的扩展名部分,包括前导点 . (即使它是整个文件名)或空字符串(如果不存在扩展名)。

(继承自 FileSystemInfo)
FullName

获取目录或文件的完整目录。

(继承自 FileSystemInfo)
IsReadOnly

获取或设置确定当前文件是否为只读的值。

LastAccessTime

获取或设置上次访问当前文件或目录的时间。

(继承自 FileSystemInfo)
LastAccessTimeUtc

获取或设置上次访问当前文件或目录的时间,其格式为协调世界时 (UTC)。

(继承自 FileSystemInfo)
LastWriteTime

获取或设置上次写入当前文件或目录的时间。

(继承自 FileSystemInfo)
LastWriteTimeUtc

获取或设置上次写入当前文件或目录的时间,其格式为协调世界时 (UTC)。

(继承自 FileSystemInfo)
Length

获取当前文件的大小(以字节为单位)。

LinkTarget

获取位于 中的 FullName链接的目标路径,如果 nullFileSystemInfo 实例不表示链接,则获取 。

(继承自 FileSystemInfo)
Name

获取文件名。

UnixFileMode

获取或设置当前文件或目录的 Unix 文件模式。

(继承自 FileSystemInfo)

方法

AppendText()

创建一个 StreamWriter,它向 FileInfo 的此实例表示的文件追加文本。

CopyTo(String)

将现有文件复制到新文件,不允许覆盖现有文件。

CopyTo(String, Boolean)

将现有文件复制到新文件,允许覆盖现有文件。

Create()

创建文件。

CreateAsSymbolicLink(String)

创建位于 中的 FullName 符号链接,该链接指向指定的 pathToTarget

(继承自 FileSystemInfo)
CreateObjRef(Type)

创建一个对象,该对象包含生成用于与远程对象进行通信的代理所需的全部相关信息。

(继承自 MarshalByRefObject)
CreateText()

创建写入新文本文件的 StreamWriter

Decrypt()

使用 Encrypt() 方法解密由当前帐户加密的文件。

Delete()

永久删除文件。

Encrypt()

将某个文件加密,使得只有加密该文件的帐户才能将其解密。

Equals(Object)

确定指定对象是否等于当前对象。

(继承自 Object)
GetAccessControl()

获取 FileSecurity 对象,该对象封装当前 FileInfo 对象所描述的文件的访问控制列表 (ACL) 项。

GetAccessControl(AccessControlSections)

获取一个 FileSecurity 对象,该对象封装当前 FileInfo 对象所描述的文件的指定类型的访问控制列表 (ACL) 项。

GetHashCode()

作为默认哈希函数。

(继承自 Object)
GetLifetimeService()
已过时.

检索控制此实例的生存期策略的当前生存期服务对象。

(继承自 MarshalByRefObject)
GetObjectData(SerializationInfo, StreamingContext)
已过时.

设置带有文件名和附加异常信息的 SerializationInfo 对象。

(继承自 FileSystemInfo)
GetType()

获取当前实例的 Type

(继承自 Object)
InitializeLifetimeService()
已过时.

获取生存期服务对象来控制此实例的生存期策略。

(继承自 MarshalByRefObject)
MemberwiseClone()

创建当前 Object 的浅表副本。

(继承自 Object)
MemberwiseClone(Boolean)

创建当前 MarshalByRefObject 对象的浅表副本。

(继承自 MarshalByRefObject)
MoveTo(String)

将指定文件移到新位置,提供要指定新文件名的选项。

MoveTo(String, Boolean)

将指定文件移动到新位置,提供指定新文件名和覆盖目标文件(如果它已存在)的选项。

Open(FileMode)

在指定的模式中打开文件。

Open(FileMode, FileAccess)

用读、写或读/写访问权限在指定模式下打开文件。

Open(FileMode, FileAccess, FileShare)

用读、写或读/写访问权限和指定的共享选项在指定的模式中打开文件。

Open(FileStreamOptions)

使用指定的创建模式、读/写和共享权限初始化 类的新实例 FileStream ,其他 FileStream 可以具有对相同文件、缓冲区大小、其他文件选项和分配大小的访问权限。

OpenRead()

创建一个只读的 FileStream

OpenText()

创建使用从现有文本文件中读取的 UTF8 编码的 StreamReader

OpenWrite()

创建一个只写的 FileStream

Refresh()

刷新对象的状态。

(继承自 FileSystemInfo)
Replace(String, String)

使用当前 FileInfo 对象所描述的文件替换指定文件的内容,这一过程将删除原始文件,并创建被替换文件的备份。

Replace(String, String, Boolean)

使用当前 FileInfo 对象所描述的文件替换指定文件的内容,这一过程将删除原始文件,并创建被替换文件的备份。 还指定是否忽略合并错误。

ResolveLinkTarget(Boolean)

获取指定链接的目标。

(继承自 FileSystemInfo)
SetAccessControl(FileSecurity)

FileSecurity 对象所描述的访问控制列表 (ACL) 项应用于当前 FileInfo 对象所描述的文件。

ToString()

返回传递给 FileInfo 构造函数的原始路径。 FullName将 或 Name 属性用作完整路径或文件名。

ToString()

返回原始路径。 使用 FullNameName 属性作为完整路径或文件/目录名。

(继承自 FileSystemInfo)

扩展方法

Create(FileInfo, FileMode, FileSystemRights, FileShare, Int32, FileOptions, FileSecurity)

创建一个新的文件流,确保使用指定的属性和安全设置创建该文件流。

GetAccessControl(FileInfo)

返回文件的安全信息。

GetAccessControl(FileInfo, AccessControlSections)

返回文件的安全信息。

SetAccessControl(FileInfo, FileSecurity)

更改现有文件的安全属性。

适用于

另请参阅