Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Environment.NewLine trong C#

Environment.NewLine là thuộc tính static trả về chuỗi ký tự xuống dòng phù hợp với **hệ điều hành hiện tại**: "\r\n" trên Windows, "\n" trên Linux/macOS. Dùng để viết code đa nền tảng (cross-platform).

Ví dụ cơ bản

string str = "Dòng 1" + Environment.NewLine + "Dòng 2";
Console.WriteLine(str);
// Windows: Dòng 1\r\nDòng 2
// Linux:   Dòng 1\nDòng 2

Mã nguồn hoàn chỉnh

using System;
using System.IO;

namespace Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = "This is demo text!" + Environment.NewLine + "This is demo text on next line!";
            Console.Write(str);
        }
    }
}

Kết quả (hiển thị trên console)

This is demo text!
This is demo text on next line!

So sánh các cách xuống dòng

CáchGiá trịĐa nền tảngKhuyến nghị
Environment.NewLine\r\n (Win) / \n (Unix)✅ CóFile text, log, cross-platform
"\n"LF chỉ⚠️ Unix-styleLinux/macOS, web, JSON
"\r\n"CRLF chỉ⚠️ Windows-styleWindows-only file (CSV, registry)
Console.WriteLine()Tự động NewLine✅ CóIn ra console
StringBuilder.AppendLine()Dùng NewLine✅ CóXây dựng chuỗi nhiều dòng

Lưu ý

  • Environment.NewLine là readonly - không thể gán giá trị.
  • Khi ghi file text cross-platform, dùng Environment.NewLine hoặc StreamWriter (tự xử lý NewLine).
  • JSON, XML, HTTP headers thường yêu cầu \n hoặc \r\n cụ thể - không dùng Environment.NewLine.
  • Trong string interpolation: $"Line1{Environment.NewLine}Line2".