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.ReadWritehoặcWrite - Dùng
FileMode.OpenhoặcOpenOrCreate - Truncate toàn bộ:
File.WriteAllText(path, "")hoặcnew FileStream(path, FileMode.Truncate)