How to check folders for write protection?

I am new to programming and work only with standard console programs written in C #.

I am currently on an internship, and I was asked to develop a small tool for them.

To be fair, the assignment is the way forward, and nothing like what I did earlier with C #.

The tool basically should do the following:

The user selects the folder to search.

The program checks all the files in the folder and all subfolders and checks the write protection if it has not yet been checked.

The program sets the read-only attribute for all files, if not currently.

If this is not the place to look for help, please ignore my question.

Thanks for reading.

+4
4

:

:

    public void SetAllFilesAsReadOnly(string rootPath)
    {
        //this will go over all files in the directory and sub directories
        foreach (string file in Directory.EnumerateFiles(rootPath, "*.*", SearchOption.AllDirectories))
        {
            //Getting an object that holds some information about the current file
            FileAttributes attr = File.GetAttributes(file);

            // set the file as read-only
            attr = attr | FileAttributes.ReadOnly;
            File.SetAttributes(file,attr);
        }
    }

, , :

, , file attribute:

var attr = File.GetAttributes(path);

enum flags

Read only:

// set read-only
attr = attr | FileAttributes.ReadOnly;
File.SetAttributes(path, attr);

Read only:

// unset read-only
attr = attr & ~FileAttributes.ReadOnly;
File.SetAttributes(path, attr);

:

 foreach (string file in Directory.EnumerateFiles(path, "*.*", SearchOption.AllDirectories))
    {
        Console.WriteLine(file);
    }
+7

FileAttributes attr = File.GetAttributes(path);
            if(attr.HasFlag( FileAttributes.ReadOnly ))
            {
             //it is readonly   
            }
+2

This MSDN stream contains the following code for obtaining folder permissions :

DirectorySecurity dSecurity = Directory.GetAccessControl(@"d:\myfolder");
foreach (FileSystemAccessRule rule in dSecurity.GetAccessRules(true, true, typeof(NTAccount)))
{
 if (rule.FileSystemRights == FileSystemRights.Read)
 {
  Console.WriteLine("Account:{0}", rule.IdentityReference.Value);
 }
}
+1
source

Check out DirectoryInfo . In particular, the Attributes property .

0
source

All Articles