How to check if a file is writtable?

I used :

if ((File.GetAttributes(file) & FileAttributes.ReadOnly) != 0)

gave me error, saying

The given path's format is not supported.



Answer this question

How to check if a file is writtable?

  • AndersBank

    Hi,

    You can use the following code segment

    string FilePath = @"C:\TEST.txt";
    System.IO.
    FileInfo Info = new System.IO.FileInfo(FilePath);
    if (!Info.IsReadOnly)
    {
    Console.WriteLine("FILE IS WRITABLE");
    }



  • icewill

    Hi

    System.IO.FileInfo fi = new System.IO.FileInfo(@"C:\abc.txt");

    if (System.IO.FileAttributes.ReadOnly == fi.Attributes)

    {

    //The file is read only.

    }

    //OR

    if (fi.IsReadOnly)

    {

    //In 2005 The File is read only

    }



  • talraviv

    I tried:

    if ((File.GetAttributes(azmanStoreFileName) & FileAttributes.ReadOnly) != 0

    but gave me error, saying

    The given path's format is not supported.

    Can anyone help Thanks


  • Lars-Inge T&#248&#59;nnessen

    Hi,

    You can use the following code segment

    string FilePath = @"C:\TEST.txt";
    System.IO.
    FileInfo Info = new System.IO.FileInfo(FilePath);
    if (Info.IsReadOnly)
    {
    Console.WriteLine("FILE IS READ-ONLY");
    }



  • BobTheBuild

    try to implement following code

    FileAttributes fa = File.GetAttributes(fileName);

    if(fa.ToString().IndexOf(FileAttributes.ReadOnly.ToString()) > -1 )

    MessageBox.Show("ReadOnly");

    hope it will works



  • StephenMas

    Hi,

    I tried your code..and it worked for me. Here's what I wrote:

    static void Main(string[] args)
    {
    string azmanStoreFileName = @"C:\Test.txt";
    if ((File.GetAttributes(azmanStoreFileName) & FileAttributes.ReadOnly) != 0)
    Console.WriteLine("readonly");
    Console.ReadLine();
    }

    Make sure you wrote everything correct. It should work.

    Maheshwari's code should also work fine. As an alternative, you can also try this:

    static void Main(string[] args)
    {
    FileInfo file = new FileInfo(@"C:\test.txt");

    // Console.WriteLine(file.Attributes.ToString());
    if ((file.Attributes & FileAttributes.ReadOnly) ==
    FileAttributes.ReadOnly)
    {
    Console.WriteLine("File is read-only (correct test).");
    }

    Console.ReadLine();
    }

    Hope that helps,
    Ashish



  • Ashok Ojha

    Hi,

    Thanx fo this simple code, it worked for me.

  • Alisa Beth

    if the file is Archive then the file is writtable.

    FileAttributes fa = File.GetAttributes(fileName);

    if (fa.ToString() == FileAttributes.Archive.ToString())

    MessageBox.Show("Writtable");



  • How to check if a file is writtable?