How do I change the Read-only file attribute for each file in a folder using c#?
Thanks
Use File.SetAttributes in a loop iterating over Directory.GetFiles
foreach (string fileName in System.IO.Directory.GetFiles(path))
{
System.IO.FileInfo fileInfo = new System.IO.FileInfo(fileName);
fileInfo.Attributes |= System.IO.FileAttributes.ReadOnly;
// or
fileInfo.IsReadOnly = true;
}
You can try this : iterate on each file and subdirectory :
public void Recurse(DirectoryInfo directory)
{
foreach (FileInfo fi in directory.GetFiles())
{
fi.IsReadOnly = false; // or true
}
foreach (DirectoryInfo subdir in directory.GetDirectories())
{
Recurse(subdir);
}
}
If you wanted to remove the readonly attributes using pattern matching (e.g. all files in the folder with a .txt extension) you could try something like this:
Directory.EnumerateFiles(path, "*.txt").ToList().ForEach(file => new FileInfo(file).Attributes = FileAttributes.Normal);