Đọc ghi nối file text .txt trong c# như thế nào?

Thảo luận trong 'Lập trình web Asp.net' bắt đầu bởi seolagi, 23/6/23.

  1. seolagi
    Tham gia ngày:
    16/4/14
    Bài viết:
    1,030
    Đã được thích:
    81
    Điểm thành tích:
    48
    Đọc ghi nối file text .txt trong c# như thế nào? hiện tại mình đang muốn đọc file .txt và ghi file vào trong file .txt này, và file được nối tiếp với nhau thì làm như thế nào?
    cho mình xin code đọc ghi file đơn giản nhanh trong c# mvc với, cảm ơn
     
    Cảm ơn đã xem bài:

    Đọc ghi nối file text .txt trong c# như thế nào?

  2. admin
    Tham gia ngày:
    22/5/13
    Bài viết:
    4,909
    Đã được thích:
    1,201
    Điểm thành tích:
    113
    Giới tính:
    Nam
    Của bạn đây nhé với

    Cách 1:
    Mã:
    //Đọc file và cho hết nội dung vào filecontent,
    string filecontent = "";
    using (var sr = new StreamReader(Server.MapPath("~/file.txt")))
    {
        string line;
        while ((line = sr.ReadLine()) != null)
        {
            filecontent +=line;
        }
    }
    //ghi lại vào file
    using (StreamWriter sw = new StreamWriter(Server.MapPath("~/file.txt")))
    {
        sw.Write(filecontent + "- Nội dung thêm mới" + Environment.NewLine);   
    }
    
    Cách 2:
    • Sử dụng thư viện:
    • using System;
    • using System.IO;
    Mã:
    using System;
    using System.IO;
    
    namespace FileHandlingArticleApp
    {
       class Program
       {
           static void Main(string[] args)
           {
               if(File.Exists("test.txt"))
               {
                   string content = File.ReadAllText("test.txt");
                   Console.WriteLine("Current content of file:");
                   Console.WriteLine(content);
               }
               Console.WriteLine("Please enter new content for the file:");
               string newContent = Console.ReadLine();
               File.WriteAllText("test.txt", newContent);
           }
       }
    }
    
    Sử dụng code khác ngoài việc sử dụng hàm WriteAllText, ta có thể sử dụng hàm khác là: AppendAllText
    Mã:
    Console.WriteLine("Please enter new content for the file - type exit and press enter to finish editing:");
    string newContent = Console.ReadLine();
    while(newContent != "exit")
    {
        File.AppendAllText("test.txt", newContent + Environment.NewLine);
        newContent = Console.ReadLine();
    }
    
     
    Chỉnh sửa cuối: 23/6/23
  3. dobolovemama
    Tham gia ngày:
    25/6/23
    Bài viết:
    1
    Đã được thích:
    0
    Điểm thành tích:
    1
    Giới tính:
    Nam
    Cảm ơn admin, bạn chỉ rất chi tiết
     


Chủ để tương tự : Đọc nối
Diễn đàn Tiêu đề Date
Lập trình web Asp.net Đọc file .txt được chọn từ FileUpload trong asp.net 19/6/17