Reputation: 79
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.
Upvotes: 5
Views: 2617
Reputation: 10456
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);
}
Upvotes: 9
Reputation: 4124
You can check it via
FileAttributes attr = File.GetAttributes(path);
if(attr.HasFlag( FileAttributes.ReadOnly ))
{
//it is readonly
}
Upvotes: 2
Reputation: 1202
This MSDN thread introduces the following code sample for acquiring 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);
}
}
Upvotes: 1