ZetCode

C# FileMode 枚举

最后修改于 2025 年 4 月 20 日

本教程解释了如何在 C# 中使用 FileMode 枚举来控制文件创建和打开行为。 FileMode 指定操作系统应如何打开文件。

FileMode 枚举与 FileStream 和其他文件相关类一起使用,以确定如何打开或创建文件。 它提供了六个选项来控制文件访问行为。

理解 FileMode 对于 C# 中正确的文件处理至关重要。 它决定是创建新文件、打开现有文件还是追加到文件。 枚举值与 FileAccess 和 FileShare 枚举一起使用,以实现完整的文件控制。

FileMode.Create 示例

FileMode.Create 指定操作系统应创建一个新文件。 如果文件存在,它将被覆盖。

Program.cs
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string path = "test1.txt";
        
        using (FileStream fs = new FileStream(path, FileMode.Create))
        {
            Console.WriteLine($"File created at: {path}");
            
            // Write some data
            byte[] data = System.Text.Encoding.UTF8.GetBytes("Hello, FileMode.Create!");
            fs.Write(data, 0, data.Length);
        }
        
        // Verify file exists
        Console.WriteLine($"File exists: {File.Exists(path)}");
    }
}

此示例创建一个新文件或覆盖现有文件。 FileMode.Create 标志确保文件在不存在时被创建。 如果文件存在,其内容将被截断为零字节。

创建 FileStream 后,我们将一些 UTF-8 编码的文本写入文件。 using 语句确保正确处置资源。 最后,我们使用 File.Exists 验证文件是否存在。

FileMode.CreateNew 示例

FileMode.CreateNew 指定操作系统应创建一个新文件。 如果文件存在,则会抛出 IOException。

Program.cs
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string path = "test2.txt";
        
        try
        {
            using (FileStream fs = new FileStream(path, FileMode.CreateNew))
            {
                Console.WriteLine($"New file created at: {path}");
                
                // Write some data
                byte[] data = System.Text.Encoding.UTF8.GetBytes("Hello, FileMode.CreateNew!");
                fs.Write(data, 0, data.Length);
            }
        }
        catch (IOException ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
    }
}

此示例尝试创建一个新文件。 如果文件已经存在,则会抛出 IOException。 此行为与 FileMode.Create 不同,后者会覆盖现有文件。

try-catch 块处理潜在的 IOException。 当您需要确保不会意外覆盖现有文件时,此模式非常有用。 它提供原子文件创建,防止覆盖。

FileMode.Open 示例

FileMode.Open 指定操作系统应打开现有文件。 如果文件不存在,则会抛出 FileNotFoundException。

Program.cs
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string path = "test3.txt";
        
        // First create the file
        File.WriteAllText(path, "Existing content");
        
        try
        {
            using (FileStream fs = new FileStream(path, FileMode.Open))
            {
                Console.WriteLine($"File opened successfully: {path}");
                
                // Read the file content
                byte[] buffer = new byte[fs.Length];
                fs.Read(buffer, 0, buffer.Length);
                string content = System.Text.Encoding.UTF8.GetString(buffer);
                Console.WriteLine($"Content: {content}");
            }
        }
        catch (FileNotFoundException ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
    }
}

此示例首先创建一个文件,然后使用 FileMode.Open 打开它。 FileStream 读取现有内容。 如果文件不存在,该操作将失败并抛出 FileNotFoundException。

该示例演示了安全的文件打开,用于读取现有内容。 当您需要处理现有文件,并且希望在文件不存在时显式失败而不是创建一个新文件时,FileMode.Open 是理想的选择。

FileMode.OpenOrCreate 示例

FileMode.OpenOrCreate 指定操作系统应打开文件(如果存在);否则,应创建一个新文件。

Program.cs
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string path = "test4.txt";
        
        using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate))
        {
            if (fs.Length == 0)
            {
                Console.WriteLine($"New file created at: {path}");
                byte[] data = System.Text.Encoding.UTF8.GetBytes("New content");
                fs.Write(data, 0, data.Length);
            }
            else
            {
                Console.WriteLine($"Existing file opened: {path}");
                
                // Read and display existing content
                byte[] buffer = new byte[fs.Length];
                fs.Read(buffer, 0, buffer.Length);
                string content = System.Text.Encoding.UTF8.GetString(buffer);
                Console.WriteLine($"Existing content: {content}");
            }
        }
    }
}

此示例检查文件是否存在。 如果存在,则打开它;否则,它创建一个新文件。 文件长度用于确定文件是新创建的还是已经存在。

当您想要处理文件而不管它是否存在时,FileMode.OpenOrCreate 非常有用,但又不想像 FileMode.Create 那样截断现有内容。 对于不确定文件是否存在的文件操作,这是一个安全的选择。

FileMode.Truncate 示例

FileMode.Truncate 指定操作系统应打开现有文件并将其大小截断为零字节。

Program.cs
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string path = "test5.txt";
        
        // First create a file with content
        File.WriteAllText(path, "This content will be truncated");
        
        try
        {
            using (FileStream fs = new FileStream(path, FileMode.Truncate))
            {
                Console.WriteLine($"File truncated: {path}");
                
                // Verify file is empty
                Console.WriteLine($"File length after truncate: {fs.Length}");
                
                // Write new content
                byte[] data = System.Text.Encoding.UTF8.GetBytes("New content after truncate");
                fs.Write(data, 0, data.Length);
            }
        }
        catch (FileNotFoundException ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
    }
}

此示例首先创建一个具有内容的文件,然后使用 FileMode.Truncate 打开它。 现有内容被擦除(文件大小变为 0),并且可以写入新内容。 如果文件不存在,则会抛出异常。

当您需要完全覆盖现有文件的内容时,FileMode.Truncate 非常有用。 与 FileMode.Create 不同,它需要文件首先存在。 此模式在清除内容的同时保留文件属性。

FileMode.Append 示例

FileMode.Append 打开现有文件并查找其末尾,或创建一个新文件。 此模式只能与仅写入访问一起使用。

Program.cs
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string path = "test6.txt";
        
        // First write initial content
        File.WriteAllText(path, "Initial line\n");
        
        using (FileStream fs = new FileStream(path, FileMode.Append))
        {
            // Append new content
            byte[] data = System.Text.Encoding.UTF8.GetBytes("Appended line\n");
            fs.Write(data, 0, data.Length);
            
            Console.WriteLine($"Content appended to: {path}");
        }
        
        // Display final content
        Console.WriteLine("Final content:");
        Console.WriteLine(File.ReadAllText(path));
    }
}

此示例演示了将内容追加到文件。 首先写入初始内容,然后使用 FileMode.Append 追加其他内容。 文件指针自动定位到文件末尾。

FileMode.Append 专门设计用于将内容添加到文件末尾。 当您只需要追加数据时,它比手动查找末尾更有效。 请注意,使用此模式,您无法从文件中读取。

将 FileMode 与 FileAccess 结合使用

FileMode 可以与 FileAccess 结合使用,以指定如何打开文件以及允许哪些操作。 此示例显示了组合。

Program.cs
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string path = "test7.txt";
        
        // Create a file with read/write access
        using (FileStream fs = new FileStream(
            path, 
            FileMode.Create, 
            FileAccess.ReadWrite))
        {
            // Write data
            byte[] data = System.Text.Encoding.UTF8.GetBytes("Initial content");
            fs.Write(data, 0, data.Length);
            
            // Reset position to read
            fs.Position = 0;
            
            // Read data back
            byte[] buffer = new byte[fs.Length];
            fs.Read(buffer, 0, buffer.Length);
            string content = System.Text.Encoding.UTF8.GetString(buffer);
            Console.WriteLine($"Read content: {content}");
        }
        
        // Open same file with read-only access
        using (FileStream fs = new FileStream(
            path, 
            FileMode.Open, 
            FileAccess.Read))
        {
            Console.WriteLine("\nOpened file in read-only mode");
            
            // Attempting to write would throw NotSupportedException
            try
            {
                byte[] data = System.Text.Encoding.UTF8.GetBytes("New content");
                fs.Write(data, 0, data.Length);
            }
            catch (NotSupportedException ex)
            {
                Console.WriteLine($"Expected error when writing: {ex.Message}");
            }
        }
    }
}

此示例首先创建一个具有读/写访问权限的文件,写入内容,然后将其读回。 然后,它以只读模式打开同一个文件,并演示不允许写入。

将 FileMode 与 FileAccess 结合使用可以精确控制文件操作。 FileAccess.ReadWrite 允许读取和写入,FileAccess.Read 提供只读访问,FileAccess.Write 提供只写访问。 这种组合对于安全的文件处理至关重要。

来源

FileMode 枚举文档

本教程涵盖了 C# 中的 FileMode 枚举,通过实际示例演示了所有六个枚举值。 理解这些模式对于 .NET 应用程序中的正确文件处理至关重要。

作者

我叫 Jan Bodnar,是一位充满热情的程序员,拥有丰富的编程经验。 我自 2007 年以来一直在撰写编程文章。 迄今为止,我撰写了超过 1,400 篇文章和 8 本电子书。 我拥有超过十年的编程教学经验。

列出所有 C# 教程