How to write protect or unprotect a file using C# or VB.NET

If you've created an important file with your application, you may want to protect the file from deletion. You don't want to prompt the user to write protect the file using the file explorer, instead you can call a function to do the work for you. The command is simply :-

The only difference between the C# and the VB.NET version of the command is the semi-colon at the end. Be sure to include a reference to the System.IO library either in the command or by using a Imports/Using command.

using System.IO;

class Program
{
    static void Main(string[] args)
    {
        File.SetAttributes("c:\\temp\\example.txt", FileAttributes.Normal);
    }
}

The VB.NET is shown as below.

Imports System.IO

Class Program
    Private Shared Sub Main(ByVal args As String())
        File.SetAttributes("c:\temp\example.txt", FileAttributes.Normal)
    End Sub
End Class

The example shown is to make a file normal so that it can be deleted. To make the file protected so it can't be deleted, the FileAttribute setting to use is FileAttributes.ReadOnly.

Its also possible to hide files using this function by changing FileAttributes.ReadOnly to FileAttributes.Hidden. It is possible to hide and write protect a file at the same time by "anding" the two attributes as below.

File.SetAttributes(sFile, FileAttributes.Hidden & FileAttributes.ReadOnly);

Note in the above, you mustn't use the && which is a conditional and as that will not work.

If the file you are setting the attributes for doesn't exist, there will be a System.IO.FileNotFoundException raised and if its not handled in a try...catch then the program will terminate.

This function is only for files, you can't write protect a folder, all you need to do there is write protect any file(s) inside to prevent the folder from being deleted. You will need to write protect every file inside the folder because write protecting one file will not write protect all the files in the folder.

Tags - .NET   File

Last Modified : June 2023


About... / Contact.. / Cookie...