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

Cắt ngắn (truncate) file trong C#

Dùng FileStream.SetLength để cắt hoặc mở rộng file.

Cú pháp

public override void SetLength(long value);

Hành vi

  • Value < Current Length: File bị cắt ngắn. Nếu position > new length, position chuyển đến byte cuối.
  • Value > Current Length: File mở rộng, position không đổi. Nội dung mở rộng là undefined.

Ví dụ

public void Export(string path)
{
    FileStream oStream = new FileStream(path, FileMode.Open, FileAccess.ReadWrite);
    oStream.SetLength(Length); // Length là long
}

Lưu ý:

  • Cần FileAccess.ReadWrite hoặc Write
  • Dùng FileMode.Open hoặc OpenOrCreate
  • Truncate toàn bộ: File.WriteAllText(path, "") hoặc new FileStream(path, FileMode.Truncate)