如何遍历d盘,并且列出有层次所有文件
用C#如何遍历d盘,并且列出有层次所有文件,而且能够用来复制出来打印,希望代码能直接运行(我不懂修改)
------解决方案--------------------/// <summary>
/// 递归目录
/// </summary>
private void AddFolder()
{
try
{
//this.folderBrowserDialog1.SelectedPath = " ";
if (this.folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
string path = folderBrowserDialog1.SelectedPath;
DirectoryInfo dinfo = new DirectoryInfo(path);
FileSystemInfo finfo = dinfo as FileSystemInfo;
ListFolderFiles(finfo);
}
}
catch (Exception)
{
}
}
private void ListFolderFiles(FileSystemInfo fileinfo)
{
if (!fileinfo.Exists) return;
DirectoryInfo dirinfo = fileinfo as DirectoryInfo;
if (dirinfo == null) return; //不是目录
FileSystemInfo[] files = dirinfo.GetFileSystemInfos();
for (int i = 0; i < files.Length; i++) //遍历目录下所有文件、子目录
{
FileInfo file = files[i] as FileInfo;
if (file != null) // 是文件
{
//操作
}
else //是目录
{
ListFolderFiles(files[i]); //对子目录进行递归调用
}
}
}
接分接分
------解决方案--------------------楼上
茅房有人,不能再等 -> 茅房有人,没有办法
更押韵
楼主参考:
private void PathToNode(string APath, TreeNodeCollection AParentNode)
{
if (!Directory.Exists(APath)) return;
string vText = Path.GetFileName(APath);
if (vText.Length <= 0) vText = APath;
TreeNode vTreeNode = AParentNode.Add(string.Format( "[{0}] ", vText));
string[] vDirectories = Directory.GetDirectories(APath);
foreach (string vPath in vDirectories)
PathToNode(vPath, vTreeNode.Nodes);
string[] vFiles = Directory.GetFiles(APath);
foreach (string vFile in vFiles)
vTreeNode.Nodes.Add(Path.GetFileName(vFile));
}
private void button4_Click(object sender, EventArgs e)
{
treeView1.BeginUpdate();
treeView1.Nodes.Clear();
try
{
PathToNode( "D: ", treeView1.Nodes);
}
finally
{
treeView1.EndUpdate();
}
}