none
Is a file (or directory) writeable? RRS feed

  • Question

  • I am using Visual Studio 2010 and am trying to find the answer to a very simple question (I thought).  Given the path of a file or a directory, is the user allowed to overwrite the file or write into the directory?

    I coded the following:

                            FileInfo fsi = new FileInfo(filename);
                            FileAttributes attrs = fsi.Attributes;
                            if ((attrs & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
                            {
                                XmlStore.LoadFailureMessage = filename + " is readonly, not supported";
                                return false;
                            }

    but it did not work when I specified a File in the drive C root directory for an unprivileged user.  Yet if I attempted to write into that directory I got a message that I did not have permission.

    Am I doing something stupid?  Thanks in advance for any help.

    Michael Bate

    Monday, April 13, 2015 12:43 AM

Answers

All replies

  • The only reliable way to test whether a file is readable is try to open a write handle to the file. There is no other reliable way because there are so many reasons that can block you from writing to it. (File permissions, attributes, share permission, existing opened handle that does not enable shared-write, etc.)

    In your case, you've hit by something known as "only process that run as SYSTEM and TRUSTEDINSTALLER can write to directory owned by TRUSTEDINSTALLER" problem that exist on Vista+. Please try to write to Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) instead.

    Monday, April 13, 2015 1:32 AM
    Answerer
  • cheong00: THANK YOU.

    But I'm not sure exactly how to create a write handle.  Should I create a FileStream object?  I would prefer not to actually write anything to a disk.  Most of the time, there will be no problem writing to the file or directory.  But I want to intercept attempts to write to a CDROM or the root directory of the C drive (if an unprivileged user).

    Thanks again.

    Monday, April 13, 2015 2:10 AM
  • Something like the following would be enough:

    bool canwrite = false; try { using (FileStream fs = File.OpenWrite("path-to-write"+"\\filename.ext")) {} canwrite = true; } finally {
    if (File.Exists("path-to-write"+"\\filename.ext"))
    {
    File.Delete("path-to-write"+"\\filename.ext"); }



    Monday, April 13, 2015 2:24 AM
    Answerer