Files, Directory, IO  

How to check if a file is read only in C#

Check if a file is read only
 
The IsReadOnly property of the FileInfo class returns if a file is read only. The following code snippet returns true if a file is read only.
  1. // File ReadOnly ?  
  2. bool IsReadOnly = fi.IsReadOnly;  
  3. Console.WriteLine("Is ReadOnly: {0}", IsReadOnly);  
Sample
 
Here is a complete sample.
  1. // Full file name   
  2. string fileName = @"C:\Temp\MaheshTXFI.txt";  
  3. FileInfo fi = new FileInfo(fileName);  
  4.   
  5. // Create a new file   
  6. using (FileStream fs = fi.Create())  
  7. {  
  8.     Byte[] txt = new UTF8Encoding(true).GetBytes("New file.");  
  9.     fs.Write(txt, 0, txt.Length);  
  10.     Byte[] author = new UTF8Encoding(true).GetBytes("Author Mahesh Chand");  
  11.     fs.Write(author, 0, author.Length);  
  12. }  
  13.   
  14. // Get File Name  
  15. string justFileName = fi.Name;  
  16. Console.WriteLine("File Name: {0}", justFileName);  
  17. // Get file name with full path   
  18. string fullFileName = fi.FullName;  
  19. Console.WriteLine("File Name: {0}", fullFileName);  
  20. // Get file extension   
  21. string extn = fi.Extension;  
  22. Console.WriteLine("File Extension: {0}", extn);  
  23. // Get directory name   
  24. string directoryName = fi.DirectoryName;  
  25. Console.WriteLine("Directory Name: {0}", directoryName);  
  26. // File Exists ?  
  27. bool exists = fi.Exists;  
  28. Console.WriteLine("File Exists: {0}", exists);  
  29. if (fi.Exists)  
  30. {  
  31.     // Get file size  
  32.     long size = fi.Length;  
  33.     Console.WriteLine("File Size in Bytes: {0}", size);  
  34.     // File ReadOnly ?  
  35.     bool IsReadOnly = fi.IsReadOnly;  
  36.     Console.WriteLine("Is ReadOnly: {0}", IsReadOnly);  
  37.     // Creation, last access, and last write time   
  38.     DateTime creationTime = fi.CreationTime;  
  39.     Console.WriteLine("Creation time: {0}", creationTime);  
  40.     DateTime accessTime = fi.LastAccessTime;  
  41.     Console.WriteLine("Last access time: {0}", accessTime);  
  42.     DateTime updatedTime = fi.LastWriteTime;  
  43.     Console.WriteLine("Last write time: {0}", updatedTime);  
Output
 
 
 

Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.