FileInfo类

1.注解

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

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

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

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

img

2.属性

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链接的目标路径,如果 null 此 FileSystemInfo 实例不表示链接,则获取 。(继承自 FileSystemInfo)
Name 获取文件名。
UnixFileMode 获取或设置当前文件或目录的 Unix 文件模式。(继承自 FileSystemInfo)

3.方法

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)
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)
ToString() 返回原始路径。 使用 FullNameName 属性作为完整路径或文件/目录名。(继承自 FileSystemInfo)

4.常用属性

  1. Exists: 判断文件是否存在。
  2. Name: 获取文件的名称。
  3. FullName: 获取文件的完整路径。
  4. Directory: 获取文件所在的目录的实例。
  5. Exists: 判断文件是否存在。
  6. Extension: 获取文件的扩展名。
  7. Length: 获取文件的大小(字节数)。
  8. CreationTime: 获取文件的创建时间。
  9. LastAccessTime: 获取文件的上次访问时间。
  10. LastWriteTime: 获取文件的上次写入时间。
using System;
using System.IO;

class Program
{
    static void Main()
    {
        // 指定文件路径
        string filePath = @"C:\example\sample.txt";

        // 创建一个 FileInfo 对象
        FileInfo fileInfo = new FileInfo(filePath);

        // 输出文件信息
        if (fileInfo.Exists)
        {
            Console.WriteLine("文件存在!")
            Console.WriteLine("文件名: " + fileInfo.Name);
            Console.WriteLine("文件完整路径: " + fileInfo.FullName);
            Console.WriteLine("文件所在目录: " + fileInfo.Directory);
            Console.WriteLine("文件是否存在: " + fileInfo.Exists);
            Console.WriteLine("文件扩展名: " + fileInfo.Extension);
            Console.WriteLine("文件大小: " + fileInfo.Length + " 字节");
            Console.WriteLine("文件创建时间: " + fileInfo.CreationTime);
            Console.WriteLine("文件上次访问时间: " + fileInfo.LastAccessTime);
            Console.WriteLine("文件上次写入时间: " + fileInfo.LastWriteTime);
        }
        else
        {
            Console.WriteLine("文件不存在!");
        }
    }
}

//文件存在!
//文件名: sample.txt
//文件完整路径: C:\example\sample.txt
//文件所在目录: C:\example
//文件是否存在: True
//文件扩展名: .txt
//文件大小: 1024 字节
//文件创建时间: 2024-04-21 10:30:00
//文件上次访问时间: 2024-04-21 11:15:00
//文件上次写入时间: 2024-04-21 11:20:00

5.常用方法

  1. System.IO.FileInfo CopyTo (string destFileName)将文件从一个位置复制到另一个位置。
using System;
using System.IO;

class Test
{

    public static void Main()
    {
        string path = @"c:\SoureFile.txt";
        string path2 = @"c:\NewFile.txt";
        FileInfo fi1 = new FileInfo(path);
        FileInfo fi2 = new FileInfo(path2);

        try
        {
            // Create the source file.
            using (FileStream fs = fi1.Create()) { }

            //Ensure that the target file does not exist.
            if (File.Exists(path2))
            {
                fi2.Delete();
            }

            //Copy the file.f
            fi1.CopyTo(path2);
            Console.WriteLine("{0} was copied to {1}.", path, path2);
        }
        catch (IOException ioex)
        {
            Console.WriteLine(ioex.Message);
        }
    }
}
  1. System.IO.FileStream Create() 创建一个新的空文件。
using System;
using System.IO;

public class DeleteTest
{
    public static void Main()
    {
        // Create a reference to a file.
        FileInfo fi = new FileInfo("temp.txt");
        // Actually create the file.
        FileStream fs = fi.Create();
        // Modify the file as required, and then close the file.
        fs.Close();
        // Delete the file.
        fi.Delete();
    }
}

以下示例创建一个文件,向其中添加一些文本,并从该文件中读取。

using System;
using System.IO;
using System.Text;

class Test
{
    
    public static void Main()
    {
        string path = @"c:\MyTest.txt";
        FileInfo fi = new FileInfo(path);

        // Delete the file if it exists.
        if (fi.Exists)
        {
            fi.Delete();
        }

        //Create the file.
        using (FileStream fs = fi.Create())
        {
            Byte[] info =
                new UTF8Encoding(true).GetBytes("This is some text in the file.");

            //Add some information to the file.
            fs.Write(info, 0, info.Length);
        }

        //Open the stream and read it back.
        using (StreamReader sr = fi.OpenText())
        {
            string s = "";
            while ((s = sr.ReadLine()) != null)
            {
                Console.WriteLine(s);
            }
        }
    }
}
//This code produces output similar to the following;
//results may vary based on the computer/file structure/etc.:
//
//This is some text in the file.
  1. void Delete() 删除文件。
using System;
using System.IO;

class Test
{
    
    public static void Main()
    {
        string path = @"c:\MyTest.txt";
        FileInfo fi1 = new FileInfo(path);

        try
        {
            using (StreamWriter sw = fi1.CreateText()) {}
            string path2 = path + "temp";
            FileInfo fi2 = new 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.ToString());
        }
    }
}
//This code produces output similar to the following;
//results may vary based on the computer/file structure/etc.:
//
//c:\MyTest.txt was copied to c:\MyTest.txttemp.
//c:\MyTest.txttemp was successfully deleted.
  1. void MoveTo(string destFileName) 将文件从一个位置移动到另一个位置。
fileInfo.MoveTo("C:\\NewLocation\\example.txt");
  1. System.IO.FileStream Open(System.IO.FileMode mode) 以指定模式打开文件,例如读取或写入文件内容。

//示例打开一个文件,向该文件添加一些信息,然后读取该文件。

using System;
using System.IO;
using System.Text;

class Test
{
    
    public static void Main()
    {
        string path = @"c:\MyTest.txt";
        FileInfo fi = new FileInfo(path);

        // Delete the file if it exists.
        if (!fi.Exists)
        {
            //Create the file.
            using (FileStream fs = fi.Create())
            {
                Byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");
                //Add some information to the file.
                fs.Write(info, 0, info.Length);
            }
        }

        //Open the stream and read it back.
        using (FileStream fs = fi.Open(FileMode.Open))
        {
            byte[] b = new byte[1024];
            UTF8Encoding temp = new UTF8Encoding(true);
            while (fs.Read(b,0,b.Length) > 0)
            {
                Console.WriteLine(temp.GetString(b));
            }
        }
    }
}
//This code produces output similar to the following;
//results may vary based on the computer/file structure/etc.:
//
//This is some text in the file.
//
//
//
//
//
//
//
//
//
//
//
//
  1. System.IO.FileStream OpenRead() 创建只读 FileStream

//以下示例以只读方式打开文件并从中读取数据。

using System;
using System.IO;
using System.Text;

class Test
{
    
    public static void Main()
    {
        string path = @"c:\MyTest.txt";
        FileInfo fi = new FileInfo(path);

        // Delete the file if it exists.
        if (!fi.Exists)
        {
            //Create the file.
            using (FileStream fs = fi.Create())
            {
                Byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");
                //Add some information to the file.
                fs.Write(info, 0, info.Length);
            }
        }

        //Open the stream and read it back.
        using (FileStream fs = fi.OpenRead())
        {
            byte[] b = new byte[1024];
            UTF8Encoding temp = new UTF8Encoding(true);

            while (fs.Read(b,0,b.Length) > 0)
            {
                Console.WriteLine(temp.GetString(b));
            }
        }
    }
}
//This code produces output similar to the following;
//results may vary based on the computer/file structure/etc.:
//
//This is some text in the file.
//
//
//
//
//
//
//
//
//
//
//
//
  1. System.IO.FileStream OpenWrite() 创建一个只写的 FileStream
using System;
using System.IO;
using System.Text;

class Test
{
    public static void Main()
    {
        string path = @"c:\Temp\MyTest.txt";
        FileInfo fi = new FileInfo(path);

        // Open the stream for writing.
        using (FileStream fs = fi.OpenWrite())
        {
            Byte[] info =
                new UTF8Encoding(true).GetBytes("This is to test the OpenWrite method.");

            // Add some information to the file.
            fs.Write(info, 0, info.Length);
        }

        // Open the stream and read it back.
        using (FileStream fs = fi.OpenRead())
        {
            byte[] b = new byte[1024];
            UTF8Encoding temp = new UTF8Encoding(true);

            while (fs.Read(b,0,b.Length) > 0)
            {
                Console.WriteLine(temp.GetString(b));
            }
        }
    }
}
//This code produces output similar to the following;
//results may vary based on the computer/file structure/etc.:
//
//This is to test the OpenWrite method.
//
//
//
//
//
//
//
//
//
//
//
  1. System.IO.StreamWriter CreateText 创建写入新文本文件的 StreamWriter
using System;
using System.IO;

class Test
{

    public static void Main()
    {
        string path = @"c:\temp\MyTest.txt";
        FileInfo fi = new FileInfo(path);

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

        //Open the file to read from.
        using (StreamReader sr = fi.OpenText())
        {
            string s = "";
            while ((s = sr.ReadLine()) != null)
            {
                Console.WriteLine(s);
            }
        }
    }
}
//This code produces output similar to the following;
//results may vary based on the computer/file structure/etc.:
//
//Hello
//And
//Welcome
posted @ 2024-04-21 17:52  好大的鱼  阅读(104)  评论(0)    收藏  举报