Check if a file is read only in CSharp
Description
The following code shows how to check if a file is read only.
Example
/* ww w .j ava 2 s. c o m*/
using System;
using System.IO;
static class MainClass
{
static void Main()
{
FileInfo file = new FileInfo("data.txt");
Console.WriteLine(file.Attributes.ToString());
// This test fails, because other attributes are set.
if (file.Attributes == FileAttributes.ReadOnly)
{
Console.WriteLine("File is read-only (faulty test).");
}
if ((file.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
{
Console.WriteLine("File is read-only (correct test).");
}
}
}
The code above generates the following result.