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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With