C# Display a cycle through of all files / folders on the computer [closed]
I currently have a C# form, although I would like to find out how I can display a cycle through of all file and folders on the computer e.g.
A text box, going through all files and folders and showing them one by one, but only one one line (so not to keep all of them in memory)
First of all what ever text you are displaying in the textbox will be in memory so your out of luck there. If you don't want to use too much memory you will have to stream the bytes somewhere else, to disk or over a network etc..
To iterate through all the files is easy in c#
public void ProcessAllFilesOnDrive()
{
ProcessFiles(@"c:\");
}
private void ProcessFiles(string path)
{
Directory.GetFiles(path).ToList().ForEach(Process);
Directory.GetDirectories(path).ToList().ForEach(ProcessFiles);
}
private void Process(string filename)
{
// do something to file
}
A iterator could do the trick. Only the most recent results would be stored in memory.
public class FileSystemList : IEnumerable<string>
{
DirectoryInfo rootDirectory;
public FileSystemList(string root)
{
rootDirectory = new DirectoryInfo(root);
}
public IEnumerator<string> GetEnumerator()
{
return ProcessDirectory(rootDirectory).GetEnumerator();
}
public IEnumerable<string> ProcessDirectory(DirectoryInfo dir)
{
yield return dir.FullName;
foreach (FileInfo file in dir.EnumerateFiles())
yield return file.FullName;
foreach (DirectoryInfo subdir in dir.EnumerateDirectories())
foreach (string result in ProcessDirectory(subdir))
yield return result;
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
I would suggest using recursion to walk the directory tree. Maybe something like this:
public static void cycleThroughDirs(DirectoryInfo dir) {
try {
foreach (DirectoryInfo dirInfo in dir.GetDirectories()) {
Console.WriteLine("Found folder: " + dirInfo.FullName);
cycleThroughDirs(dirInfo);
}
} catch (Exception) {}
try {
foreach (FileInfo fileInfo in dir.GetFiles()) {
Console.WriteLine("Found file: " + fileInfo.FullName);
}
} catch (Exception) {}
}
I know you are wanting to put this in a text box so you'll have to tweak this to fit that need. But this should get you to what you are needing.
精彩评论