正在递归设置文件属性子文件夹
本文关键字:文件夹 置文件属性 递归 | 更新日期: 2023-09-27 18:19:44
我在尝试为文件夹设置属性时遇到问题,文件夹中的文件设置为Readonly。我可以设置文件夹属性,但不能设置其中的文件。
这将设置包括子文件夹在内的属性,然后删除。找到了有关代码项目的信息。
使用这个:
ScanDirectory scanDirectory = new ScanDirectory();
scanDirectory.WalkDirectory(@"/Storage Card");
public class ScanDirectory
{
public void WalkDirectory(string directory)
{
WalkDirectory(new DirectoryInfo(directory));
}
private void WalkDirectory(DirectoryInfo directory)
{
// Scan all files in the current path
foreach (FileInfo file in directory.GetFiles())
{
file.Attributes &= ~FileAttributes.ReadOnly;
file.Delete();
}
DirectoryInfo[] subDirectories = directory.GetDirectories();
// Scan the directories in the current directory and call this method
// again to go one level into the directory tree
foreach (DirectoryInfo subDirectory in subDirectories)
{
WalkDirectory(subDirectory);
subDirectory.Attributes &= ~FileAttributes.ReadOnly;
subDirectory.Delete();
}
}
}
您可以创建一个递归函数来完成这项工作:
private void UpdateFileAttributes(DirectoryInfo dInfo)
{
// Set Directory attribute
dInfo.Attributes &= ~FileAttributes.ReadOnly;
// get list of all files in the directory and clear
// the Read-Only flag
foreach (FileInfo file in dInfo.GetFiles())
{
file.Attributes &= ~FileAttributes.ReadOnly;
}
// recurse all of the subdirectories
foreach (DirectoryInfo subDir in dInfo.GetDirectories())
{
UpdateFileAttributes(subDir);
}
}
您可以使用深度优先搜索(堆栈版本)或呼吸优先搜索(队列版本)遍历树来查看您的文件夹,类似于以下内容:
static void Main(String[] args)
{
// Using breath-first search (BFS)
Queue<DirectoryInfo> myQueue = new Queue<DirectoryInfo>();
// Your storage path here
myQueue.Enqueue(new DirectoryInfo("C:''"));
while(myQueue.Count > 0)
{
// Look at the current directory
DirectoryInfo crtDI = myQueue.Dequeue();
// Put the directories from the crt dir in a queue
foreach (DirectoryInfo otherDir in GetCrtDirectories(crtDI))
myQueue.Enqueue(otherDir);
// Do what you want with the directory here
FixAccess(crtDI);
}
}
private static IEnumerable<DirectoryInfo> GetCrtDirectories(DirectoryInfo crtDI)
{
foreach(string dirStr in Directory.GetDirectories(crtDI.FullName))
{
DirectoryInfo newDir = new DirectoryInfo(dirStr);
yield return newDir;
}
}
private static void FixAccess (DirectoryInfo DI)
{
foreach (string fileName in System.IO.Directory.GetFiles(DI.FullName))
{
FileInfo fileInfo = new FileInfo(fileName);
FileAttributes attributes = fileInfo.Attributes;
if ((attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
{
// set the attributes to nonreadonly
fileInfo.Attributes &= ~FileAttributes.ReadOnly;
}
}
}