728x90

FileInfo is a class in the System.IO namespace that provides properties and instance methods for the creation, copying, deletion, moving, and opening of files. It also provides methods for creating FileStream objects. Unlike the File class, which is static, FileInfo works with specific file instances.

Key Properties:

  • Name: Gets the name of the file.
  • Length: Gets the size of the file in bytes.
  • Extension: Gets the extension part of the file.
  • Directory: Gets an instance of the parent directory.
  • FullName: Gets the full path of the file.
  • CreationTime: Gets or sets the creation time of the file.
  • LastAccessTime: Gets or sets the last access time of the file.
  • LastWriteTime: Gets or sets the last write time of the file.

Common Methods:

  1. Create:
  2. // Creates a new file FileInfo fileInfo = new FileInfo("example.txt"); using (FileStream fs = fileInfo.Create()) { // Write to the file here }
  3. CopyTo:
  4. // Copies the file to a new location fileInfo.CopyTo("example_copy.txt");
  5. Delete:
  6. // Deletes the file fileInfo.Delete();
  7. MoveTo:
  8. // Moves the file to a new location fileInfo.MoveTo(@"C:\NewDirectory\example.txt");
  9. Open:
  10. // Opens the file with the specified FileMode using (FileStream fs = fileInfo.Open(FileMode.Open)) { // Read or write to the file here }

Example Usage:

Here's an example demonstrating how to use some of these properties and methods:

using System;
using System.IO;

class Program
{
    static void Main()
    {
        FileInfo fileInfo = new FileInfo("example.txt");

        // Create the file and write some text
        using (FileStream fs = fileInfo.Create())
        {
            byte[] info = new UTF8Encoding(true).GetBytes("Hello, FileInfo!");
            fs.Write(info, 0, info.Length);
        }

        // Display file information
        Console.WriteLine("File Name: " + fileInfo.Name);
        Console.WriteLine("File Full Name: " + fileInfo.FullName);
        Console.WriteLine("File Size: " + fileInfo.Length);
        Console.WriteLine("File Extension: " + fileInfo.Extension);
        Console.WriteLine("Creation Time: " + fileInfo.CreationTime);

        // Move the file to a new location
        fileInfo.MoveTo(@"C:\NewDirectory\example.txt");

        // Check if the file exists
        if (fileInfo.Exists)
        {
            Console.WriteLine("The file exists.");
        }

        // Delete the file
        fileInfo.Delete();
        Console.WriteLine("File deleted.");
    }
}
728x90
반응형

'Software > C#' 카테고리의 다른 글

C# 시작하기 - Namespace : System  (0) 2025.01.11
C# 시작하기 - DirectoryInfo  (0) 2025.01.11
C# 시작하기 - System.IO  (0) 2025.01.11
C# 시작하기 - System.IO.Directory  (0) 2025.01.11
C# 시작하기 - System.IO.File  (0) 2025.01.11

+ Recent posts