Skip to content

文件输入和输出

使用目录、文件和路径类管理本地目录和文件

在本地存储数据涉及在本地文件系统上管理文件和目录。 这包括创建、删除、移动、读取、写入、复制和操作文件和目录。 .NET Framework 在 System.IO 命名空间中提供了一组丰富的类,以方便这些操作。

了解 Path 类

.NET 中的 Path 类用于处理文件和目录路径。 它提供检索和修改路径信息的方法。

下面是 Path 类中一些最常用的方法:

  • Combine:用于将多个字符串合并到单个路径中。
  • GetDirectoryName:用于从路径获取目录信息。
  • GetFileName:用于从路径获取文件名和扩展名。
  • GetFileNameWithoutExtension:用于获取没有扩展名的文件名。
  • GetExtension:用于获取文件的扩展名。
  • GetFullPath:用于获取文件的完全限定路径。
  • GetTempPath:用于获取当前系统的临时文件夹的路径。
  • GetTempFileName:用于创建临时文件并返回其路径。

下面是如何使用 Path 类合并路径和获取文件信息的示例:

c#
using System;
using System.IO;
class Program
{
    static void Main()
    {
        string directoryPath = @"C:\ExampleDirectory";
        string fileName = "example.txt";

        // Combine directory and file name to create a full path
        string fullPath = Path.Combine(directoryPath, fileName);
        Console.WriteLine("Full Path: " + fullPath);

        // Get the file name without extension
        string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fullPath);
        Console.WriteLine("File Name Without Extension: " + fileNameWithoutExtension);

        // Get the file extension
        string fileExtension = Path.GetExtension(fullPath);
        Console.WriteLine("File Extension: " + fileExtension);
    }
}

了解 Directory 类

.NET 中的 Directory 类提供用于创建、删除、移动和枚举目录的方法。 这些方法可用于管理应用程序中的目录。

下面是 Directory 类中一些最常用的方法:

  • Exists:用于检查目录是否存在。
  • CreateDirectory:用于创建新目录。
  • GetCurrentDirectory:用于获取当前工作目录。
  • GetFiles:用于获取指定目录中的文件名数组。
  • Delete:用于删除现有目录。
  • Move:用于移动或重命名目录。
  • EnumerateDirectories:用于列出指定路径中的所有目录。
  • EnumerateFiles:用于列出指定路径中的所有文件。
  • GetDirectories:用于获取指定目录中的目录名称数组。
  • GetParent:用于获取指定路径的父目录。

以下示例演示如何使用该 Directory 类创建目录、检查是否存在并枚举其文件:

c#
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string directoryPath = @"C:\ExampleDirectory";

        // Create a new directory
        Directory.CreateDirectory(directoryPath);

        // Check if the directory exists
        if (Directory.Exists(directoryPath))
        {
            Console.WriteLine("Directory exists.");

            // Enumerate files in the directory
            foreach (string file in Directory.EnumerateFiles(directoryPath))
            {
                Console.WriteLine(file);
            }
        }
        else
        {
            Console.WriteLine("Directory does not exist.");
        }
    }
}

了解 File 类

.NET 中的 File 类提供了执行各种文件作的方法,例如读取、写入、复制和删除文件。

下面是类中 File 一些最常用的方法:

  • Exists:用于检查文件是否存在。
  • Create:用于创建新文件。
  • Delete:用于删除文件。
  • Copy:用于将文件复制到新位置。
  • Move:用于移动或重命名文件。
  • ReadAllText:用于从文件读取所有文本。
  • WriteAllText:用于将文本写入文件。
  • AppendText:用于向文件追加文本。
  • ReadAllLines:用于将文件中的所有行读取到字符串数组中。
  • WriteAllLines:用于将字符串数组写入文件。
  • ReadAllBytes:用于将文件中的所有字节读取到字节数组中。
  • WriteAllBytes:用于将字节数组写入文件。
  • Open:用于打开文件进行读取或写入。
  • OpenRead:用于打开要读取的文件。
  • OpenWrite:用于打开文件进行写入。
  • OpenText:用于打开用于读取文本的文件。
  • GetAttributes:用于获取文件的属性。
  • SetAttributes:用于设置文件的属性。

以下示例演示如何使用 File 类创建文件、向其写入文本以及读回文本:

c#
using System;
using System.IO;
class Program
{
    static void Main()
    {
        string filePath = @"C:\ExampleFile.txt";

        // Create a new file and write text to it
        File.WriteAllText(filePath, "Hello, World!");

        // Read the text from the file
        string text = File.ReadAllText(filePath);
        Console.WriteLine(text);
    }
}

结合使用 Path、Directory 和 File 类

应用程序通常需要结合文件和目录操作。 这些PathDirectoryFile类可以一起使用,来执行复杂的文件 I/O操作。

以下示例演示如何创建目录、在该目录中创建文件、将文本写入文件以及读回文本:

c#
using System;
using System.IO;
class Program
{
    static void Main()
    {
        string directoryPath = @"C:\ExampleDirectory";
        string fileName = "example.txt";
        string filePath = Path.Combine(directoryPath, fileName);

        // Create a new directory
        Directory.CreateDirectory(directoryPath);

        // Create a new file and write text to it
        File.WriteAllText(filePath, "Hello, World!");

        // Read the text from the file
        string text = File.ReadAllText(filePath);
        Console.WriteLine(text);
    }
}

使用 StreamReader 和 StreamWriter 类读取和写入文本文件

在 C# 应用程序中,文本文件通常用于存储和交换数据。 命名空间 System.IO 提供用于读取和写入文本文件的类,让开发人员能够轻松操作文本数据。 用于此目的的两个常用类是 StreamReaderStreamWriter

StreamReader 类用于从特定编码中的字节流读取字符,而该 StreamWriter 类用于将字符写入特定编码中的流。 这些 StreamReaderStreamWriter 类可用于处理文本文件,例如逗号分隔值(CSV)文件,其中数据按行和列进行组织。

什么是流?

在 .NET 中,流用于表示可从中读取或写入的字节序列。 流提供了一种以灵活、高效的方式处理数据的方法,允许以各种格式(包括文本、二进制和网络流)读取和写入数据。 该 Stream 类是 .NET 中所有流的基类,它提供读取和写入数据的方法,以及查找流中特定位置的方法。

Stream 类是抽象类,这意味着无法直接实例化。 而是使用派生类(例如FileStreamMemoryStreamNetworkStream和其他类)来处理特定类型的数据源。

这些 StreamReaderStreamWriter 类基于 Stream 类构建,提供用于读取和写入文本数据的其他功能。

使用 StreamWriter 编写文本文件

StreamWriter 类用于将字符写入特定编码中的流。 它提供按行或字符逐个字符写入文本文件的方法。 该 StreamWriter 类可用于编写大型文件,因为它允许以内存高效的方式写入数据。

StreamWriter 类包括以下方法:

Write():将指定的字符串写入当前流。 WriteLine():将指定的字符串后跟行终止符写入当前流。 Flush():清除当前编写器的所有缓冲区,并导致任何缓冲数据写入基础设备。

以下示例演示如何使用 StreamWriter 类将数据写入 CSV 文件:

c#
using System;
using System.IO;
using System.Text;

class Program
{
    static void Main()
    {
        string filePath = "data.csv";

        using (StreamWriter writer = new StreamWriter(filePath, false, Encoding.UTF8))
        {
            // Write some data
            writer.WriteLine("Name,Age,Occupation");
            writer.WriteLine("Elize Harmsen,30,Engineer");
            writer.WriteLine("Peter Zammit,25,Designer");
            writer.WriteLine("Niki Demetriou,35,Manager");
        }

        Console.WriteLine($"CSV file created at: {filePath}");
    }
}

使用 StreamReader 读取文本文件

StreamReader 类用于从特定编码中的字节流读取字符。 它提供按行或字符逐个字符读取文本文件的方法。 该 StreamReader 类可用于读取大型文件,因为它允许以内存高效的方式读取数据。

StreamReader 类包括以下方法:

Read():从输入流中读取下一个字符,并将读取器的位置提升一个字符。 ReadLine():从当前流中读取一行字符,并将其作为字符串返回。 ReadToEnd():从当前位置读取流末尾的所有字符,并将其作为字符串返回。 Peek():返回下一个可用字符,而不移动读取器的位置。

以下示例演示如何使用 StreamReader 类逐行读取 CSV 文件:

c#
using System;
using System.IO;
using System.Text;

class Program
{
    static void Main()
    {
        string filePath = "data.csv";

        using (StreamReader reader = new StreamReader(filePath, Encoding.UTF8))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                Console.WriteLine(line);
            }
        }
    }
}

使用 FileStream 类控制文件访问

FileStream 类是 System.IO 命名空间的一部分,用于文件输入和输出作。 与更高级别的抽象(如StreamReaderStreamWriter)相比, FileStream 类允许你以更精细的方式处理文件。

若要创建 FileStream 对象,通常指定文件路径、打开文件(例如FileMode.OpenFileMode.Create)和访问级别(例如,FileAccess.ReadFileAccess.Write)的模式。 该 FileStream 类提供用于读取和写入文件字节的方法,以及用于控制文件访问的属性。

FileStream 属性和方法

FileStream 类提供了多个属性和方法,可用于控制文件访问和执行读/写作。 下面是类的 FileStream 一些关键属性和方法:

FileStream 类包含以下关键属性:

  • Length:获取用字节表示的流长度。
  • Position:获取或设置流中的当前位置。
  • CanRead:指示流是否支持读取。如果流可以被读取,则此属性返回 true,否则返回 false。
  • CanWrite:指示流是否支持写入。如果流可写,则此属性返回 true,否则返回 false。
  • CanSeek:指示流是否支持搜寻。如果流支持查找,则此属性返回true;否则返回false。(磁盘文件始终支持随机访问。 属性值 CanSeek 设置为 true 或 false 取决于基础文件类型。)

FileStream 类包括以下关键方法:

  • Read:从流中读取字节块并将数据写入缓冲区。例如,fs.Read(buffer, 0, buffer.Length) 将数据读入缓冲区。
  • Write:使用缓冲区中的数据将字节块写入流。例如,fs.Write(data, 0, data.Length) 将数据从数据数组写入文件。
  • Seek:设置当前流中的位置。例如,fs.Seek(0, SeekOrigin.Begin) 将位置移动到文件的开头。
  • Flush:清除当前流的所有缓冲区,并将所有缓冲的数据写入文件。
  • Close:关闭当前流并释放与其关联的任何资源。
  • Dispose:释放 FileStream 对象使用的资源。在直接或间接销毁 FileStream 对象时,会自动调用此方法。

使用 FileStream 类检查文件读取和写入操作

  • 以下是如何使用 FileStream 将数据写入文件中:
c#
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string path = "example.txt";
        byte[] data = System.Text.Encoding.UTF8.GetBytes("Hello, FileStream!");

        using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
        {
            fs.Write(data, 0, data.Length);
        }

        Console.WriteLine("Data written to file.");
    }
}
  • 以下是如何使用 FileStream 从文件中读取数据:
c#
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string path = "example.txt";
        byte[] buffer = new byte[1024]; // Adjust buffer size as needed

        using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
        {
            int bytesRead = fs.Read(buffer, 0, buffer.Length);
            string readData = System.Text.Encoding.UTF8.GetString(buffer, 0, bytesRead);
            Console.WriteLine("Data read from file: " + readData);
        }
    }
}
  • 下面是一个更全面的编码示例,演示如何在文件中读取、写入和查找:
c#
using System;
using System.IO;
using System.Threading.Tasks;

class Program
{
    static Task Main()
    {
        string path = "example.txt";
        byte[] data = System.Text.Encoding.UTF8.GetBytes("Hello, FileStream!");

        // Writing to the file
        using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
        {
            fs.Write(data, 0, data.Length);
            fs.Flush();
        }

        // Reading from the file
        using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
        {
            byte[] buffer = new byte[data.Length];
            fs.Seek(0, SeekOrigin.Begin);
            int bytesRead = fs.Read(buffer, 0, buffer.Length);
            string readData = System.Text.Encoding.UTF8.GetString(buffer, 0, bytesRead);
            Console.WriteLine("Data read from file: " + readData);
        }
    }
}

使用 FileStream 属性实现文件访问控制

FileStream 类提供用于控制文件访问的其他属性。 这些属性包括:

CanRead:指示流是否支持读取。属性在流可以读取时返回 true,否则返回 false。 CanWrite:指示流是否支持写入。此属性在流可以写入时返回true,否则返回false。 CanSeek:指示流是否支持搜寻。如果流支持搜寻,则此属性会返回 true;否则返回 false。 FileAccess:指定文件的访问级别。它可以设置为 Read、Write或ReadWrite。 FileShare:指定其他线程对文件具有的访问级别。 它可以设置为None、Read、Write或ReadWrite。 FileMode:指定作系统应如何打开文件。它可以设置为Append、Create、CreateNew、Open、OpenOrCreate或Truncate。 FileOptions:指定用于打开文件的选项。它可以设置为None、Asynchronous、SequentialScan、RandomAccess或WriteThrough。

以下是使用 FileStream 属性实现如何访问控制的示例:

c#
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string path = "example.txt";
        byte[] data = System.Text.Encoding.UTF8.GetBytes("Hello, FileStream!");

        // Writing to the file
        using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None, 4096, false))
        {
            fs.Write(data, 0, data.Length);
            fs.Flush();
        }

        // Reading from the file
        using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.None, 4096, false))
        {
            byte[] buffer = new byte[data.Length];
            fs.Seek(0, SeekOrigin.Begin);
            int bytesRead = fs.Read(buffer, 0, buffer.Length);
            string readData = System.Text.Encoding.UTF8.GetString(buffer, 0, bytesRead);
            Console.WriteLine("Data read from file: " + readData);
        }
    }
}

BinaryReader 和 BinaryWriter 类

二进制文件是包含人类不可读格式数据的文件。 它们通常用于存储复杂的数据结构、图像、音频、视频和其他类型的内容。 与文本文件相比,二进制文件在存储和性能方面可以更高效,尤其是在处理大量数据时。 二进制文件通常不是由人类打开和读取的,因为它们可能包含特定于特定应用程序或系统的格式的数据。 相反,它们旨在由理解二进制格式的软件进行处理。

这些 BinaryReaderBinaryWriter 类属于 .NET 的 System.IO 命名空间,旨在读取和写入二进制数据。 开发人员需了解何时以及如何使用 BinaryReaderBinaryWriter 来有效操作文件和数据流。

使用 BinaryReader 和 BinaryWriter

在此示例中,我们创建一个名为example.dat的二进制文件,并使用BinaryWriter将整数、双精度和字符串写入其中。 然后,我们使用 BinaryReader 读回数据并将其打印到控制台。

c#
using System;
using System.IO;
using System.Text;

public class BinaryReaderWriterExample
{
    public static void Main()
    {
        // Create a file to write to
        using (FileStream fs = new FileStream("example.dat", FileMode.Create))
        {
            using (BinaryWriter writer = new BinaryWriter(fs))
            {
                // Write some data
                writer.Write(42); // Integer
                writer.Write(3.14); // Double
                writer.Write("Hello, World!"); // String
            }
        }

        // Read the data back
        using (FileStream fs = new FileStream("example.dat", FileMode.Open))
        {
            using (BinaryReader reader = new BinaryReader(fs))
            {
                int intValue = reader.ReadInt32();
                double doubleValue = reader.ReadDouble();
                string stringValue = reader.ReadString();

                Console.WriteLine($"Integer: {intValue}");
                Console.WriteLine($"Double: {doubleValue}");
                Console.WriteLine($"String: {stringValue}");
            }
        }
    }
}

将 BinaryReader 和 BinaryWriter 与 Encoding 配合使用

在此示例中,我们创建了一个名为 example.dat 的二进制文件,并使用 BinaryWriter 以 UTF-8 编码向其中写入一个整数、一个双精度数和一个字符串。 然后,我们使用相同编码的 BinaryReader 读回数据,并将其打印到控制台。

c#
using System;
using System.IO;
using System.Text;

public class BinaryReaderWriterEncodingExample
{
    public static void Main()
    {
        // Create a file to write to
        using (FileStream fs = new FileStream("example.dat", FileMode.Create))
        {
            using (BinaryWriter writer = new BinaryWriter(fs, Encoding.UTF8))
            {
                // Write some data with UTF-8 encoding
                writer.Write(42); // Integer
                writer.Write(3.14); // Double
                writer.Write("Hello, World!"); // String
            }
        }

        // Read the data back
        using (FileStream fs = new FileStream("example.dat", FileMode.Open))
        {
            using (BinaryReader reader = new BinaryReader(fs, Encoding.UTF8))
            {
                int intValue = reader.ReadInt32();
                double doubleValue = reader.ReadDouble();
                string stringValue = reader.ReadString();

                Console.WriteLine($"Integer: {intValue}");
                Console.WriteLine($"Double: {doubleValue}");
                Console.WriteLine($"String: {stringValue}");
            }
        }
    }
}

将 BinaryReader 和 BinaryWriter 与 FileStream 配合使用

在此示例中,我们创建一个名为 example.dat 的二进制文件,并使用 FileStreamBinaryWriter 向其中写入整数、双精度和字符串。 然后,我们使用相同 FileStreamBinaryReader 读回数据,并将其打印到控制台。

c#
using System;
using System.IO;
using System.Text;

public class BinaryReaderWriterFileStreamExample
{
    public static void Main()
    {
        // Create a file to write to
        using (FileStream fs = new FileStream("example.dat", FileMode.Create))
        {
            using (BinaryWriter writer = new BinaryWriter(fs))
            {
                // Write some data
                writer.Write(42); // Integer
                writer.Write(3.14); // Double
                writer.Write("Hello, World!"); // String
            }
        }

        // Read the data back
        using (FileStream fs = new FileStream("example.dat", FileMode.Open))
        {
            using (BinaryReader reader = new BinaryReader(fs))
            {
                int intValue = reader.ReadInt32();
                double doubleValue = reader.ReadDouble();
                string stringValue = reader.ReadString();

                Console.WriteLine($"Integer: {intValue}");
                Console.WriteLine($"Double: {doubleValue}");
                Console.WriteLine($"String: {stringValue}");
            }
        }
    }
}

Last updated:

Released under the MIT License.