Làm thế nào để đọc một tập tin văn bản bằng phương thức ReadAllLines trong CSharp?(How to read text file with ReadAllLines method in CSharp?)


Bài viết này chúng ta sẽ tìm hiểu cách sử dụng phương thức ReadAllLines() để đọc các tâp tin văn bản(text) trong ngôn ngữ lập trình CSharp.





File.ReadAllLines()

Là một phương thức cơ bản của lớp File(class file) được sử dụng để chuyển đổi tất cả các nội dung trong một tập thành kiểu dữ liệu dạng mảng kiểu chuỗi(string array) trong CSharp.


Cú pháp - Syntax

public static string[] ReadAllLines(
    string path
)


Ví dụ - Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
// @author: developer.bnson@gmail.com
// @web: vnlives.net

namespace HowToReadFile
{
    class Program
    {
        static void Main(string[] args)
        {

            // Đọc mỗi dòng của tập tin thành mảng string.
            // Mỗi phần tử trong mảng là một dòng của tập tin.
            // Read each line of the file into a string array.
            // Each element of the array is one line of the file.
            string[] lines = System.IO.File.ReadAllLines(@"D:\TEXT_FILE_DEMO.txt");

            // Hiển thị nội dung tập tin bằng vòng lập foreach.
            // Display the file contents by using a foreach loop.
            System.Console.WriteLine("Contents of file = ");
            foreach (string line in lines)
            {
                // Use a tab to indent each line of the file.
                Console.WriteLine("\t" + line);
            }

            // Keep the console window open in debug mode.
            Console.WriteLine("Press any key to exit.");
            System.Console.ReadKey();

        }
    }
}


Kết quả - Result



















No comments:

Post a Comment