那么我如何递归搜索文件夹并取消隐藏目录中的所有文件和子文件夹?比如让它检查每个文件和文件夹。。。如果它们被藏起来的话。。解开它们。Iv整个上午都在胡搞,运气不好。。。我让所有文件夹都恢复正常,但仅此而已。
foreach (var filePath in Directory.GetFiles(@"C:Temp2"))
{
Console.Write("File " + filePath);
FileAttributes fileAttribute = File.GetAttributes(filePath);
if ((fileAttribute & FileAttributes.Hidden) > 0)
{
Console.WriteLine(" is hidden.");
// unset the hidden flag, but do not change other flags:
File.SetAttributes(filePath, fileAttribute & ~FileAttributes.Hidden);
}
else
{
Console.WriteLine(" is not hidden.");
}
}
要递归执行,请使用
Directory.GetFiles(@"C:Temp2", "*", SearchOption.AllDirectories)
要包含目录,请使用GetFileSystemEntries
Directory.GetFileSystemEntries(@"C:Temp2", "*", SearchOption.AllDirectories)
这样的东西怎么样?
foreach (var file in directory.GetFiles())
{
if ((File.GetAttributes(file.FullName) & FileAttributes.Hidden) == FileAttributes.Hidden)
{
File.SetAttributes(file.FullName, FileAttributes.Normal);
}
}
使用递归很容易解决这个问题。
诸如"hidden"之类的文件属性被指定为枚举标志,并且通常使用位操作来设置或清除。您可以通过获取该路径的FileInfo或DirectoryInfo来查看文件或目录的属性。
// startDir assumed to be full path
public static void UnhideAll(string startDir)
{
DirectoryInfo dir = new DirectoryInfo(startDir);
Console.WriteLine("Working in {0}", startDir);
// First, clear hidden flag on the current directory (if needed)
if ((dir.Attributes & FileAttributes.Hidden) != 0)
{
Console.WriteLine("Clearing hidden flag on dir");
dir.Attributes &= ~FileAttributes.Hidden;
}
else
Console.WriteLine("No need to clear flag since it's already non-hidden");
// Second, recursively go into all sub directories
foreach (var subDir in dir.GetDirectories())
UnhideAll(subDir.FullName);
// Third, fix all hidden files in the current folder
foreach (var file in dir.GetFiles())
{
if ((file.Attributes & FileAttributes.Hidden) != 0)
{
Console.WriteLine("Clearing hidden flag on file {0}", file.FullName);
file.Attributes &= ~FileAttributes.Hidden;
}
else
Console.WriteLine("Skipping {0} since it's not hidden", file.FullName);
}
}
现在,您可以通过调用递归地取消隐藏目录中的所有隐藏文件
UnhideAll(@"C:SomePathThatShouldBeUnhidden");
当然,当您使用此代码时,您会希望删除对Console.WriteLine
的所有调用,但我将它们保留在那里是为了让您更容易地了解代码运行时发生了什么。这里有一个更精简的版本:
// startDir assumed to be full path
public static void UnhideAll(string startDir)
{
DirectoryInfo dir = new DirectoryInfo(startDir);
// First, clear the current directory
dir.Attributes &= ~FileAttributes.Hidden;
// Second, recursively go into all sub directories
foreach (var subDir in dir.GetDirectories())
UnhideAll(subDir.FullName);
// Third, fix all hidden files in this folder
foreach (var file in dir.GetFiles())
file.Attributes &= ~FileAttributes.Hidden;
}