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

Mở file ẩn trong C#

Để mở file ẩn, trước hết bỏ thuộc tính ẩn:

FileInfo file = new FileInfo(Environment.CurrentDirectory + @"\myFile.txt");
file.Attributes &= ~FileAttributes.Hidden;

Đọc file bình thường:

using (StreamReader sr = new StreamReader("myFile.txt"))
{
    string line;
    while ((line = sr.ReadLine()) != null)
    {
        Console.WriteLine(line);
    }
}

Sau khi đọc, ẩn lại file:

file.Attributes |= FileAttributes.Hidden;

Giải thích bitwise:

  • &= ~Hidden: Clear bit Hidden (bỏ ẩn)
  • |= Hidden: Set bit Hidden (ẩn)

Cách khác: Dùng File.SetAttributes(path, FileAttributes.Normal) để bỏ tất cả thuộc tính đặc biệt.