How to: Determine if a Directory is Read-Only in Visual Basic
The GetDirectoryInfo method returns a DirectoryInfo object with a Attributes property that can be queried to determine information about the directory, including whether it is read-only.
Note
Your computer might show different names or locations for some of the Visual Studio user interface elements in the following instructions. The Visual Studio edition that you have and the settings that you use determine these elements. For more information, see Visual Studio Settings.
To determine if a directory is read-only
Use the GetDirectoryInfo method to return a DirectoryInfo object for the specified directory. This example returns a DirectoryInfo object for the directory TestDirectory.
Dim reader As System.IO.DirectoryInfo reader = My.Computer.FileSystem.GetDirectoryInfo("C:\testDirectory")
Query the Attributes property of the object to determine whether it is read-only.
If (reader.Attributes And System.IO.FileAttributes.ReadOnly) > 0 Then MsgBox("Directory is readonly!") End If
Example
The following example, which presents the above snippet in complete form, determines whether the directory testDirectory is read-only and reports the result in a message box.
Dim reader As System.IO.DirectoryInfo
reader = My.Computer.FileSystem.GetDirectoryInfo("C:\testDirectory")
If (reader.Attributes And System.IO.FileAttributes.ReadOnly) > 0 Then
MsgBox("File is readonly!")
End If
Compiling the Code
If the directory does not exist, an exception is not thrown until the first time a property on the DirectoryInfo object is accessed.
Robust Programming
The following conditions may cause an exception:
The path is not valid for one of the following reasons: it is a zero-length string; it contains only white space; it contains invalid characters; or it is a device path (starts with \\.\) (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
The path exceeds the system-defined maximum length (PathTooLongException).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
The user lacks necessary permissions to view the path (SecurityException).
See Also
Tasks
How to: Determine a Directory's Attributes in Visual Basic