Set File Attributes in C#

The System.IO namespace is a crucial part of the .NET Framework, providing a range of types that facilitate reading from and writing to files and data streams, as well as offering basic file and directory support.

One important class within the System.IO namespace is the FileInfo class. This class is designed for typical file operations, making it easier to perform tasks such as copying, moving, renaming, creating, opening, deleting, and appending to files. By utilizing the methods and properties provided by the FileInfo class, developers can efficiently handle file-related operations in their applications.

FileInfo class

For example, the FileInfo class provides methods like CopyTo() and MoveTo() to copy and move files, respectively. It also offers properties such as Name, Length, and Directory to obtain information about the file, such as its name, size, and parent directory.

_file.Attributes = System.IO.FileAttributes.Hidden;

Another key aspect of file and directory support within the System.IO namespace is the FileSystemInfo class. This class serves as a base class for both FileInfo and DirectoryInfo and provides properties and methods common to both file and directory operations. One important property of the FileSystemInfo class is Attributes, which allows developers to retrieve or modify the attributes of a file or directory. This includes attributes such as read-only, hidden, archived, and more.

The following C# program shows how to set readonly and hidden property to a file .

Full Source C#
using System; using System.Windows.Forms; using System.IO; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { try { FileInfo _file = new FileInfo("c:\\test1.txt"); _file.Attributes = System.IO.FileAttributes.ReadOnly; _file.Attributes = System.IO.FileAttributes.Hidden; } catch (System.IO.FileNotFoundException ex) { MessageBox.Show(ex.StackTrace); } } } }


The System.IO namespace provides a comprehensive set of tools for working with files, directories, and data streams. By using the capabilities of classes such as FileInfo and FileSystemInfo, developers can efficiently handle file operations and manage the attributes of files and directories in their C# applications.