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ách | Giá trị | Đa nền tảng | Khuyến nghị |
|---|---|---|---|
Environment.NewLine | \r\n (Win) / \n (Unix) | ✅ Có | File text, log, cross-platform |
"\n" | LF chỉ | ⚠️ Unix-style | Linux/macOS, web, JSON |
"\r\n" | CRLF chỉ | ⚠️ Windows-style | Windows-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.NewLinelàreadonly- không thể gán giá trị.- Khi ghi file text cross-platform, dùng
Environment.NewLinehoặcStreamWriter(tự xử lý NewLine). - JSON, XML, HTTP headers thường yêu cầu
\nhoặc\r\ncụ thể - không dùngEnvironment.NewLine. - Trong string interpolation:
$"Line1{Environment.NewLine}Line2".