Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check folders for write-protection?

Tags:

c#

.net

I'm a newbie to programming, and have only been working with standard console programs written with C#.

I am currently on an internship, and I've been asked to design a little Tool for them.

To be fair, the assignment is way over my ahead, and nothing like what I have previously made with C#.

The Tool basicly has to do the following:

User choses a folder to be searched.

Program checks all files in the folder, and all sub folders, and checks the Write-protection if not already checked.

Program sets read-only attribute on all files, if there is not currently.

If this is not the place to search for help, please disregard my question.

Thanks for reading.

like image 505
JFBN Avatar asked Dec 20 '22 19:12

JFBN


1 Answers

This is pretty much a copy paste from this thread:

The complete code should look something like:

    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);
        }
    }

Following your comments, Just for better understanding, let's break it into bits and pieces:

once you have the file path, create the file attribute object:

var attr = File.GetAttributes(path);

For the following, you might want to read a bit about enum flags and bitwise

this is how you set as Read only:

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

this is how you un-set as Read only:

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

And for getting all files you can use:

 foreach (string file in Directory.EnumerateFiles(path, "*.*", SearchOption.AllDirectories))
    {
        Console.WriteLine(file);
    }
like image 99
Avi Turner Avatar answered Jan 03 '23 23:01

Avi Turner