C# 查看目录文件及文件大小
private void button1_Click(object sender, EventArgs e)
{
BuildTreeView(textBox1.Text);
}
long AddDirectory(DirectoryInfo dir, TreeNode tNode)
{
FileSystemInfo[] fSIs = dir.GetFileSystemInfos();
FileSystemInfo fSI;
int i;
long directorySize = 0;
for (i = 0; i < fSIs.Length;i++ )
{
fSI = fSIs[i];
if (fSI.GetType()==typeof(FileInfo))
{
FileInfo fInfo = (FileInfo)fSI;
string s = fInfo.Name + FileSizeString(fInfo.Length);
TreeNode newTreeNode = new TreeNode(s);
tNode.Nodes.Add(newTreeNode);
directorySize += fInfo.Length;
}
else if (fSI.GetType()==typeof(DirectoryInfo))
{
DirectoryInfo dirInfo = (DirectoryInfo)fSI;
TreeNode dirTreeNode = new TreeNode(dirInfo.Name);
long dirSize = AddDirectory(dirInfo, dirTreeNode);
dirTreeNode.Text += FileSizeString(dirSize);
tNode.Nodes.Add(dirTreeNode);
directorySize += dirSize;
}
else
{
MessageBox.Show("Ooops");
}
}
return directorySize;
}
string FileSizeString(long fileSize)
{
const long OneMB = 1024 * 1024;
const long OneGB = OneMB * 1024;
string unit;
double dispSize;
if (fileSize<1024)
{
unit = "B";
dispSize = fileSize;
}
else if (fileSize<OneMB)
{
unit = "KB";
dispSize = fileSize / 1024;
}
else if(fileSize<OneGB)
{
unit = "MB";
dispSize = fileSize / OneMB;
}
else
{
unit = "GB";
dispSize = fileSize / OneGB;
}
return string.Format("({0,4:F}",dispSize)+unit+")";
}
private void BuildTreeView(string dirName)
{
DirectoryInfo dirInfo = new DirectoryInfo(dirName);
TreeNode tNode = new TreeNode(dirName);
long totalSize = AddDirectory(dirInfo, tNode);
tNode.Text += FileSizeString(totalSize);
treeView1.Nodes.Clear();
treeView1.Nodes.Add(tNode);
}
private void button2_Click(object sender, EventArgs e)
{
folderBrowser();
}
//选择目录对话框
private void folderBrowser()
{
FolderBrowserDialog folderDlg = new FolderBrowserDialog();
folderDlg.ShowDialog();
textBox1.Text = folderDlg.SelectedPath;
BuildTreeView(textBox1.Text);
}
}