C# 技术使用笔记:File Read-Write 文件读写从入门到专家

在当今数字化时代,文件处理是软件开发中不可或缺的一部分。无论是简单的文本文件,还是复杂的二进制文件,亦或是结构化的 XML、JSON 文件,开发者都需要掌握高效处理文件的技术。C# 作为一门功能强大的编程语言,提供了丰富的类库和工具来满足这些需求。本文将详细介绍如何在 C# 中处理各种类型的文件,包括文件的读取、写入、修改和保存操作。通过具体的代码示例和详细解析,帮助读者快速掌握文件处理的核心技能,提升开发效率。

1. 文件读写基础

1.1 使用FileStream读写文件

在C#中,FileStream类是处理文件读写操作的基础类,它提供了对文件的字节流访问,可以用于读取、写入、更新文件内容。以下是关于如何使用FileStream进行文件读写操作的详细说明。

文件写入操作

  • 创建文件并写入内容:使用FileStream的构造函数可以指定文件路径、打开方式等参数。当以写入模式打开一个不存在的文件时,会自动创建该文件。例如,以下代码展示了如何创建一个文本文件并写入内容:

using System;
using System.IO;

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

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

在上述代码中,FileStream的构造函数指定了文件路径、打开方式为FileMode.Create(表示创建文件,如果文件已存在则覆盖),访问权限为FileAccess.Write。通过调用Write方法将字节数组data写入文件。

  • 追加内容到文件:如果希望在已有文件的基础上追加内容,可以将FileMode设置为Append。例如:

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string filePath = "example.txt";
        string content = " This is an appended line.";
        byte[] data = System.Text.Encoding.UTF8.GetBytes(content);

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

此时,FileStream会定位到文件末尾,将新内容追加到文件中。

文件读取操作

  • 读取文件内容:可以通过FileStreamRead方法读取文件中的字节数据。例如,以下代码展示了如何读取一个文本文件的内容:

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string filePath = "example.txt";
        byte[] data = new byte[1024]; // 假设文件内容不会超过1024字节
        int bytesRead;

        using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
        {
            bytesRead = fs.Read(data, 0, data.Length);
        }

        string content = System.Text.Encoding.UTF8.GetString(data, 0, bytesRead);
        Console.WriteLine(content);
    }
}

在上述代码中,FileStream的构造函数指定了文件路径、打开方式为FileMode.Open(表示打开一个已存在的文件),访问权限为FileAccess.Read。通过调用Read方法将文件中的字节数据读取到字节数组data中,然后通过Encoding.UTF8.GetString方法将字节数组转换为字符串。

  • 按行读取文件内容:虽然FileStream本身不提供直接按行读取的功能,但可以结合StreamReader类来实现。StreamReader类封装了FileStream,提供了更方便的文本读取功能。例如:

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string filePath = "example.txt";

        using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
        using (StreamReader sr = new StreamReader(fs))
        {
            string line;
            while ((line = sr.ReadLine()) != null)
            {
                Console.WriteLine(line);
            }
        }
    }
}

在上述代码中,StreamReader通过FileStream打开文件,并通过ReadLine方法逐行读取文件内容。

文件更新操作

  • 修改文件内容:如果需要修改文件中的部分内容,可以先读取整个文件内容,然后对内容进行修改,最后将修改后的内容写回文件。例如,以下代码展示了如何修改文件中的某一行内容:

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string filePath = "example.txt";
        string[] lines = File.ReadAllLines(filePath); // 读取文件的所有行

        // 修改第2行的内容
        if (lines.Length >= 2)
        {
            lines[1] = "This is the new second line.";
        }

        File.WriteAllLines(filePath, lines); // 将修改后的内容写回文件
    }
}

在上述代码中,File.ReadAllLines方法用于读取文件的所有行内容,File.WriteAllLines方法用于将修改后的内容写回文件。需要注意的是,这种方式会覆盖整个文件内容,因此在修改文件时需要谨慎操作。

文件删除操作

  • 删除文件:如果需要删除一个文件,可以使用File.Delete方法。例如:

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string filePath = "example.txt";

        if (File.Exists(filePath))
        {
            File.Delete(filePath);
            Console.WriteLine("File deleted successfully.");
        }
        else
        {
            Console.WriteLine("File does not exist.");
        }
    }
}

在上述代码中,File.Exists方法用于检查文件是否存在,File.Delete方法用于删除文件。

通过以上内容,我们可以了解到FileStream类在C#中处理文件读写操作的基本方法。它提供了对文件的字节流访问,可以满足常见的文件操作需求。在实际开发中,可以根据具体需求选择合适的方法来处理文件。

2. 文本文件处理

2.1 读取文本文件内容

在C#中,读取文本文件内容是常见的文件操作之一。除了在第1章中提到的使用FileStream结合StreamReader按行读取文件内容的方法外,还可以使用File.ReadAllText方法直接读取整个文本文件的内容。

  • 使用File.ReadAllText读取整个文件内容:该方法可以方便地读取文本文件的全部内容,并将其作为一个字符串返回。例如:

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string filePath = "example.txt";

        if (File.Exists(filePath))
        {
            string content = File.ReadAllText(filePath);
            Console.WriteLine("File content:");
            Console.WriteLine(content);
        }
        else
        {
            Console.WriteLine("File does not exist.");
        }
    }
}

在上述代码中,File.ReadAllText方法直接读取了指定路径的文件内容,并将其存储在字符串变量content中。这种方法适用于文件内容较小的情况,因为它会将整个文件内容加载到内存中。

  • 读取特定编码的文本文件:如果文本文件使用了特定的编码(如UTF-8、ASCII等),可以通过指定编码来正确读取文件内容。例如:

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string filePath = "example.txt";

        if (File.Exists(filePath))
        {
            string content = File.ReadAllText(filePath, System.Text.Encoding.UTF8);
            Console.WriteLine("File content:");
            Console.WriteLine(content);
        }
        else
        {
            Console.WriteLine("File does not exist.");
        }
    }
}

在上述代码中,通过指定System.Text.Encoding.UTF8作为编码参数,可以正确读取使用UTF-8编码的文本文件内容。

2.2 向文本文件追加内容

向文本文件追加内容是文件处理中的一个常见需求。除了在第1章中提到的使用FileStreamFileMode.Append模式打开文件并追加内容外,还可以使用File.AppendAllText方法来实现。

  • 使用File.AppendAllText追加内容:该方法可以直接将指定的字符串内容追加到文本文件的末尾。例如:

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string filePath = "example.txt";
        string contentToAppend = "This is the appended content.";

        File.AppendAllText(filePath, contentToAppend + Environment.NewLine); // 追加内容并换行
        Console.WriteLine("Content appended successfully.");
    }
}

在上述代码中,File.AppendAllText方法将字符串contentToAppend追加到文件末尾,并通过Environment.NewLine添加了一个换行符,以确保追加的内容与原有内容分隔清晰。

  • 追加特定编码的内容:如果需要以特定的编码追加内容,可以通过指定编码参数来实现。例如:

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string filePath = "example.txt";
        string contentToAppend = "This is the appended content.";

        File.AppendAllText(filePath, contentToAppend + Environment.NewLine, System.Text.Encoding.UTF8); // 以UTF-8编码追加内容
        Console.WriteLine("Content appended successfully.");
    }
}

在上述代码中,通过指定System.Text.Encoding.UTF8作为编码参数,可以确保以UTF-8编码追加内容,这对于处理包含特殊字符的文本文件非常有用。

通过以上方法,可以方便地读取和追加文本文件的内容。在实际开发中,可以根据文件的大小、编码以及具体需求选择合适的方法来处理文本文件。

3. 二进制文件处理

3.1 读取二进制文件内容

在C#中,读取二进制文件内容通常需要使用FileStream类结合BinaryReader类来实现。BinaryReader类封装了FileStream,提供了更方便的读取二进制数据的方法。以下是关于如何读取二进制文件内容的详细说明。

  • 读取基本数据类型BinaryReader类提供了多种方法来读取基本数据类型(如intfloatstring等)。例如,以下代码展示了如何读取一个包含基本数据类型的二进制文件:

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string filePath = "example.bin";

        using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
        using (BinaryReader br = new BinaryReader(fs))
        {
            int intValue = br.ReadInt32();
            float floatValue = br.ReadSingle();
            string stringValue = br.ReadString();

            Console.WriteLine($"Int value: {intValue}");
            Console.WriteLine($"Float value: {floatValue}");
            Console.WriteLine($"String value: {stringValue}");
        }
    }
}

在上述代码中,FileStream的构造函数指定了文件路径、打开方式为FileMode.Open(表示打开一个已存在的文件),访问权限为FileAccess.ReadBinaryReader通过FileStream打开文件,并通过ReadInt32ReadSingleReadString等方法分别读取intfloatstring类型的数据。

  • 读取自定义结构:如果二进制文件中存储的是自定义结构的数据,可以通过定义一个与文件结构对应的结构体来读取。例如,以下代码展示了如何读取一个包含自定义结构的二进制文件:

using System;
using System.IO;

[StructLayout(LayoutKind.Sequential)]
struct Person
{
    public int Id;
    public string Name;
    public float Age;
}

class Program
{
    static void Main()
    {
        string filePath = "example.bin";

        using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
        using (BinaryReader br = new BinaryReader(fs))
        {
            Person person = new Person();
            person.Id = br.ReadInt32();
            person.Name = br.ReadString();
            person.Age = br.ReadSingle();

            Console.WriteLine($"Person ID: {person.Id}");
            Console.WriteLine($"Person Name: {person.Name}");
            Console.WriteLine($"Person Age: {person.Age}");
        }
    }
}

在上述代码中,定义了一个Person结构体,其成员与二进制文件中的数据结构相对应。通过BinaryReaderReadInt32ReadStringReadSingle等方法分别读取IdNameAge字段的值,并将其赋值给Person结构体的成员。

3.2 写入二进制文件内容

在C#中,写入二进制文件内容通常需要使用FileStream类结合BinaryWriter类来实现。BinaryWriter类封装了FileStream,提供了更方便的写入二进制数据的方法。以下是关于如何写入二进制文件内容的详细说明。

  • 写入基本数据类型BinaryWriter类提供了多种方法来写入基本数据类型(如intfloatstring等)。例如,以下代码展示了如何写入一个包含基本数据类型的二进制文件:

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string filePath = "example.bin";
        int intValue = 42;
        float floatValue = 3.14f;
        string stringValue = "Hello, World!";

        using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
        using (BinaryWriter bw = new BinaryWriter(fs))
        {
            bw.Write(intValue);
            bw.Write(floatValue);
            bw.Write(stringValue);
        }

        Console.WriteLine("Data written to binary file successfully.");
    }
}

在上述代码中,FileStream的构造函数指定了文件路径、打开方式为FileMode.Create(表示创建文件,如果文件已存在则覆盖),访问权限为FileAccess.WriteBinaryWriter通过FileStream打开文件,并通过Write方法分别写入intfloatstring类型的数据。

  • 写入自定义结构:如果需要将自定义结构的数据写入二进制文件,可以通过定义一个结构体并使用BinaryWriterWrite方法来实现。例如,以下代码展示了如何写入一个包含自定义结构的二进制文件:

using System;
using System.IO;

[StructLayout(LayoutKind.Sequential)]
struct Person
{
    public int Id;
    public string Name;
    public float Age;
}

class Program
{
    static void Main()
    {
        string filePath = "example.bin";
        Person person = new Person { Id = 1, Name = "John Doe", Age = 25.5f };

        using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
        using (BinaryWriter bw = new BinaryWriter(fs))
        {
            bw.Write(person.Id);
            bw.Write(person.Name);
            bw.Write(person.Age);
        }

        Console.WriteLine("Person data written to binary file successfully.");
    }
}

在上述代码中,定义了一个Person结构体,并创建了一个Person实例。通过BinaryWriterWrite方法分别写入IdNameAge字段的值,将自定义结构的数据存储到二进制文件中。

通过以上方法,可以方便地读取和写入二进制文件的内容。在实际开发中,可以根据文件的结构和具体需求选择合适的方法来处理二进制文件。

4. XML文件处理

4.1 读取XML文件内容

在C#中,读取XML文件内容可以通过多种方式实现,其中最常用的是使用System.Xml命名空间中的XmlDocument类和XDocument类。以下是两种方法的详细说明。

使用XmlDocument类读取XML文件

XmlDocument类提供了对XML文档的读取和操作功能。以下是一个示例代码,展示如何使用XmlDocument读取XML文件内容:

using System;
using System.Xml;

class Program
{
    static void Main()
    {
        string filePath = "example.xml";

        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load(filePath); // 加载XML文件

        // 获取根节点
        XmlNode root = xmlDoc.DocumentElement;

        // 遍历所有子节点
        foreach (XmlNode node in root.ChildNodes)
        {
            Console.WriteLine($"Node Name: {node.Name}, Node Value: {node.InnerText}");
        }
    }
}

在上述代码中,XmlDocument.Load方法用于加载XML文件,DocumentElement属性获取根节点,然后通过遍历ChildNodes集合来访问每个子节点的内容。

使用XDocument类读取XML文件

XDocument类是LINQ to XML的一部分,提供了更灵活的XML处理方式。以下是一个示例代码,展示如何使用XDocument读取XML文件内容:

using System;
using System.Linq;
using System.Xml.Linq;

class Program
{
    static void Main()
    {
        string filePath = "example.xml";

        XDocument xDoc = XDocument.Load(filePath); // 加载XML文件

        // 获取根节点
        XElement root = xDoc.Root;

        // 遍历所有子节点
        foreach (XElement element in root.Elements())
        {
            Console.WriteLine($"Element Name: {element.Name}, Element Value: {element.Value}");
        }
    }
}

在上述代码中,XDocument.Load方法用于加载XML文件,Root属性获取根节点,然后通过Elements方法获取子节点集合并遍历输出。

示例XML文件

假设example.xml文件内容如下:

<Students>
    <Student>
        <Name>John Doe</Name>
        <Age>20</Age>
    </Student>
    <Student>
        <Name>Jane Smith</Name>
        <Age>22</Age>
    </Student>
</Students>

运行上述代码后,将输出:

Element Name: Student, Element Value: John Doe20
Element Name: Student, Element Value: Jane Smith22

4.2 修改XML文件内容

在C#中,修改XML文件内容可以通过XmlDocument类或XDocument类来实现。以下是两种方法的详细说明。

使用XmlDocument类修改XML文件内容

以下是一个示例代码,展示如何使用XmlDocument修改XML文件中的某个节点内容:

using System;
using System.Xml;

class Program
{
    static void Main()
    {
        string filePath = "example.xml";

        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load(filePath); // 加载XML文件

        // 获取根节点
        XmlNode root = xmlDoc.DocumentElement;

        // 查找并修改第一个Student节点的Name值
        XmlNode studentNode = root.SelectSingleNode("Student/Name");
        if (studentNode != null)
        {
            studentNode.InnerText = "New Name"; // 修改节点内容
        }

        xmlDoc.Save(filePath); // 保存修改后的XML文件
        Console.WriteLine("XML file updated successfully.");
    }
}

在上述代码中,SelectSingleNode方法用于查找指定路径的节点,然后通过修改InnerText属性来更新节点内容,最后调用Save方法将修改后的XML文件保存到磁盘。

使用XDocument类修改XML文件内容

以下是一个示例代码,展示如何使用XDocument修改XML文件中的某个节点内容:

using System;
using System.Linq;
using System.Xml.Linq;

class Program
{
    static void Main()
    {
        string filePath = "example.xml";

        XDocument xDoc = XDocument.Load(filePath); // 加载XML文件

        // 查找并修改第一个Student节点的Name值
        XElement studentElement = xDoc.Descendants("Student").FirstOrDefault()?.Element("Name");
        if (studentElement != null)
        {
            studentElement.Value = "New Name"; // 修改节点内容
        }

        xDoc.Save(filePath); // 保存修改后的XML文件
        Console.WriteLine("XML file updated successfully.");
    }
}

在上述代码中,Descendants方法用于查找所有Student节点,FirstOrDefault方法获取第一个节点,然后通过Element方法获取Name子节点并修改其Value属性,最后调用Save方法保存修改后的XML文件。

4.3 保存修改后的XML文件

在修改XML文件内容后,需要将修改后的XML文件保存到磁盘。无论是使用XmlDocument类还是XDocument类,都可以通过调用Save方法来实现。

使用XmlDocument.Save方法保存文件

xmlDoc.Save(filePath);

使用XDocument.Save方法保存文件

xDoc.Save(filePath);

在保存文件时,需要注意以下几点:

  • 如果文件路径不存在,Save方法会自动创建文件。

  • 如果文件已存在,Save方法会覆盖原有文件。

  • 在保存文件之前,建议对文件路径进行检查,确保路径有效且具有写入权限。

通过以上方法,可以方便地读取、修改和保存XML文件内容。在实际开发中,可以根据具体需求选择合适的方法来处理XML文件。

5. JSON文件处理

5.1 读取JSON文件内容

在C#中,读取JSON文件内容通常借助System.Text.Json命名空间中的JsonDocument类或Newtonsoft.Json库中的JsonConvert.DeserializeObject方法来实现。以下是两种方法的详细说明。

使用JsonDocument类读取JSON文件

JsonDocument类是.NET Core 3.0及以上版本中用于解析JSON的类,它提供了对JSON文档的只读访问。以下是一个示例代码,展示如何使用JsonDocument读取JSON文件内容:

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

class Program
{
    static void Main()
    {
        string filePath = "example.json";

        using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
        using (JsonDocument document = JsonDocument.Parse(fs))
        {
            JsonElement root = document.RootElement;

            // 遍历JSON对象的属性
            foreach (JsonProperty property in root.EnumerateObject())
            {
                Console.WriteLine($"Property Name: {property.Name}, Property Value: {property.Value}");
            }
        }
    }
}

在上述代码中,JsonDocument.Parse方法用于解析JSON文件流,RootElement属性获取JSON文档的根元素,然后通过EnumerateObject方法遍历根元素的属性。

使用Newtonsoft.Json库读取JSON文件

Newtonsoft.Json是一个广泛使用的JSON处理库,它提供了更灵活的JSON解析功能。以下是一个示例代码,展示如何使用Newtonsoft.Json读取JSON文件内容:

using System;
using System.IO;
using Newtonsoft.Json.Linq;

class Program
{
    static void Main()
    {
        string filePath = "example.json";

        string jsonContent = File.ReadAllText(filePath);
        JObject jsonObject = JObject.Parse(jsonContent);

        // 遍历JSON对象的属性
        foreach (var property in jsonObject.Properties())
        {
            Console.WriteLine($"Property Name: {property.Name}, Property Value: {property.Value}");
        }
    }
}

在上述代码中,File.ReadAllText方法用于读取JSON文件的全部内容,JObject.Parse方法将字符串解析为JSON对象,然后通过Properties方法遍历JSON对象的属性。

示例JSON文件

假设example.json文件内容如下:

{
    "Name": "John Doe",
    "Age": 25,
    "IsStudent": true
}

运行上述代码后,将输出:

Property Name: Name, Property Value: John Doe
Property Name: Age, Property Value: 25
Property Name: IsStudent, Property Value: True

5.2 修改JSON文件内容

在C#中,修改JSON文件内容可以通过System.Text.Json命名空间中的JsonDocument类或Newtonsoft.Json库中的JObject类来实现。以下是两种方法的详细说明。

使用JsonDocument类修改JSON文件内容

JsonDocument类提供了对JSON文档的只读访问,因此不能直接修改JSON内容。如果需要修改JSON内容,可以使用JsonElementClone方法将其转换为可修改的JsonElement,然后进行修改。以下是一个示例代码,展示如何使用JsonDocument修改JSON文件内容:

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

class Program
{
    static void Main()
    {
        string filePath = "example.json";

        using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
        using (JsonDocument document = JsonDocument.Parse(fs))
        {
            JsonElement root = document.RootElement.Clone();

            // 修改JSON对象的属性值
            if (root.TryGetProperty("Name", out JsonElement nameElement))
            {
                root[nameElement.GetRawText()] = "New Name";
            }

            // 将修改后的JSON内容写回文件
            using (FileStream fsWrite = new FileStream(filePath, FileMode.Create, FileAccess.Write))
            {
                JsonSerializer.Serialize(fsWrite, root);
            }
        }

        Console.WriteLine("JSON file updated successfully.");
    }
}

在上述代码中,Clone方法将JsonElement转换为可修改的副本,然后通过索引器修改属性值,最后使用JsonSerializer.Serialize方法将修改后的JSON内容写回文件。

使用Newtonsoft.Json库修改JSON文件内容

Newtonsoft.Json库提供了更灵活的JSON修改功能。以下是一个示例代码,展示如何使用Newtonsoft.Json修改JSON文件内容:

using System;
using System.IO;
using Newtonsoft.Json.Linq;

class Program
{
    static void Main()
    {
        string filePath = "example.json";

        string jsonContent = File.ReadAllText(filePath);
        JObject jsonObject = JObject.Parse(jsonContent);

        // 修改JSON对象的属性值
        jsonObject["Name"] = "New Name";

        // 将修改后的JSON内容写回文件
        File.WriteAllText(filePath, jsonObject.ToString());

        Console.WriteLine("JSON file updated successfully.");
    }
}

在上述代码中,JObject.Parse方法将字符串解析为JSON对象,然后通过索引器修改属性值,最后使用File.WriteAllText方法将修改后的JSON内容写回文件。

5.3 保存修改后的JSON文件

在修改JSON文件内容后,需要将修改后的JSON文件保存到磁盘。无论是使用System.Text.Json还是Newtonsoft.Json,都可以通过将修改后的JSON对象序列化为字符串并写入文件来实现。

使用System.Text.Json保存修改后的JSON文件

using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
    JsonSerializer.Serialize(fs, modifiedJsonElement);
}

使用Newtonsoft.Json保存修改后的JSON文件

File.WriteAllText(filePath, modifiedJsonObject.ToString());

在保存文件时,需要注意以下几点:

  • 如果文件路径不存在,保存方法会自动创建文件。

  • 如果文件已存在,保存方法会覆盖原有文件。

  • 在保存文件之前,建议对文件路径进行检查,确保路径有效且具有写入权限。

6. CSV文件处理

6.1 读取CSV文件内容

在C#中,读取CSV文件内容可以通过多种方式实现,其中最常用的是使用System.IO命名空间中的类来逐行读取文件内容,然后解析每行数据。以下是关于如何读取CSV文件内容的详细说明。

使用StreamReader逐行读取CSV文件

StreamReader类提供了方便的文件读取功能,可以逐行读取CSV文件的内容。以下是一个示例代码,展示如何使用StreamReader读取CSV文件:

using System;
using System.IO;

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

        using (StreamReader sr = new StreamReader(filePath))
        {
            string line;
            while ((line = sr.ReadLine()) != null)
            {
                string[] values = line.Split(','); // 使用逗号分隔每行数据
                Console.WriteLine($"Row: {string.Join(", ", values)}");
            }
        }
    }
}

在上述代码中,StreamReader通过ReadLine方法逐行读取CSV文件的内容,然后使用Split方法以逗号为分隔符将每行数据分割成多个字段,并输出每一行的内容。

使用File.ReadAllLines读取CSV文件

File.ReadAllLines方法可以一次性读取整个CSV文件的所有行,并将其存储在一个字符串数组中。以下是一个示例代码,展示如何使用File.ReadAllLines读取CSV文件:

using System;
using System.IO;

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

        string[] lines = File.ReadAllLines(filePath); // 读取所有行

        foreach (string line in lines)
        {
            string[] values = line.Split(','); // 使用逗号分隔每行数据
            Console.WriteLine($"Row: {string.Join(", ", values)}");
        }
    }
}

在上述代码中,File.ReadAllLines方法读取了CSV文件的所有行,并将其存储在字符串数组lines中。然后通过遍历数组并使用Split方法解析每行数据。

示例CSV文件

假设example.csv文件内容如下:

Name,Age,Country
John Doe,25,USA
Jane Smith,30,UK

运行上述代码后,将输出:

Row: Name, Age, Country
Row: John Doe, 25, USA
Row: Jane Smith, 30, UK

6.2 向CSV文件追加内容

向CSV文件追加内容是文件处理中的一个常见需求。在C#中,可以通过使用StreamWriter类以追加模式打开文件来实现。以下是关于如何向CSV文件追加内容的详细说明。

使用StreamWriter追加内容

StreamWriter类提供了方便的文件写入功能,可以通过设置FileMode.Append以追加模式打开文件。以下是一个示例代码,展示如何向CSV文件追加内容:

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string filePath = "example.csv";
        string contentToAppend = "Alice Johnson,22,Canada";

        using (StreamWriter sw = new StreamWriter(filePath, true)) // true表示以追加模式打开文件
        {
            sw.WriteLine(contentToAppend); // 追加内容
        }

        Console.WriteLine("Content appended successfully.");
    }
}

在上述代码中,StreamWriter的构造函数中设置了true作为第二个参数,表示以追加模式打开文件。通过调用WriteLine方法将新内容追加到文件末尾。

使用File.AppendAllText追加内容

File.AppendAllText方法提供了一种更简洁的方式来向文件追加内容。以下是一个示例代码,展示如何使用File.AppendAllText向CSV文件追加内容:

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string filePath = "example.csv";
        string contentToAppend = "Alice Johnson,22,Canada";

        File.AppendAllText(filePath, contentToAppend + Environment.NewLine); // 追加内容并换行

        Console.WriteLine("Content appended successfully.");
    }
}

在上述代码中,File.AppendAllText方法将指定的字符串内容追加到文件末尾,并通过Environment.NewLine添加一个换行符,以确保追加的内容与原有内容分隔清晰。

通过以上方法,可以方便地向CSV文件追加内容。在实际开发中,可以根据具体需求选择合适的方法来处理CSV文件。

7. 总结

在本教程中,我们深入探讨了在 C# 中处理各种类型文件的方法,涵盖了从基础的文件读写操作到对特定格式文件(如文本文件、二进制文件、XML 文件、JSON 文件和 CSV 文件)的详细操作。通过逐步的代码示例和详细解释,我们展示了如何高效地进行文件内容的增删改查以及保存操作。

通过学习 FileStreamStreamReaderStreamWriterBinaryReaderBinaryWriterXmlDocumentXDocumentJsonDocumentJObject 等类的使用,读者可以掌握在 C# 中处理文件的核心技术。这些技术不仅适用于简单的文件操作,还可以扩展到更复杂的业务场景中,帮助开发者高效地处理文件数据。

在实际开发中,选择合适的方法和工具来处理文件至关重要。对于文本文件,File.ReadAllTextFile.AppendAllText 提供了便捷的读取和追加功能;对于二进制文件,BinaryReaderBinaryWriter 能够精确地读写基本数据类型和自定义结构;对于 XML 和 JSON 文件,XmlDocumentXDocumentJsonDocumentJObject 提供了强大的解析和修改能力;而对于 CSV 文件,简单的字符串分割和追加操作即可满足需求。

通过本教程的学习,读者可以更好地理解和应用 C# 中的文件处理技术,从而在实际项目中高效地处理各种文件类型。

猜你喜欢

转载自blog.csdn.net/caifox/article/details/146723956
今日推荐