19. Xử lý file trong ngôn ngữ lập trình C#

Trong ngôn ngữ lập trình C#, bạn có thể xử lý tập tin (file) bằng cách sử dụng các lớp và phương thức có sẵn trong namespace System.IO. Dưới đây là một số cách cơ bản để thực hiện xử lý file trong lập trình C#:

  1. Đọc nội dung tập tin:
csharp
using System;
using System.IO;

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

        try {
            string content = File.ReadAllText(filePath);
            Console.WriteLine("File content: " + content);
        }
        catch (Exception e) {
            Console.WriteLine("Error reading the file: " + e.Message);
        }
    }
}
  1. Ghi nội dung vào tập tin:
csharp
using System;
using System.IO;

class Program {
    static void Main() {
        string filePath = "path_to_your_file.txt";
        string contentToWrite = "This is the content to write.";

        try {
            File.WriteAllText(filePath, contentToWrite);
            Console.WriteLine("File written successfully.");
        }
        catch (Exception e) {
            Console.WriteLine("Error writing the file: " + e.Message);
        }
    }
}
  1. Kiểm tra sự tồn tại của tập tin:
csharp
using System;
using System.IO;

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

        if (File.Exists(filePath)) {
            Console.WriteLine("File exists.");
        }
        else {
            Console.WriteLine("File does not exist.");
        }
    }
}
  1. Đọc và ghi từng dòng trong tập tin:
csharp
using System;
using System.IO;

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

        try {
            // Đọc từng dòng và in ra màn hình
            foreach (string line in File.ReadLines(filePath)) {
                Console.WriteLine("Line: " + line);
            }

            // Ghi dòng mới vào tập tin
            using (StreamWriter writer = File.AppendText(filePath)) {
                writer.WriteLine("New line added.");
            }
        }
        catch (Exception e) {
            Console.WriteLine("Error: " + e.Message);
        }
    }
}

Lưu ý rằng khi làm việc với tập tin, cần xử lý các exception có thể xảy ra, ví dụ như tập tin không tồn tại, quyền truy cập bị từ chối, và nhiều tình huống khác trong lập trình C#.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top