读书人

查询文件夹中的文件数量,该如何解决

发布时间: 2012-04-25 19:32:32 作者: rapoo

查询文件夹中的文件数量
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace WindowsFormsApplication4
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{

}
public void Searchfile(string Directory)
{
int countfile = 0;//文件数量
int countdir = 0;//文件夹数量
DirectoryInfo dir = new DirectoryInfo(Directory);
FileSystemInfo[] fi = dir.GetFileSystemInfos();//获取文件夹下的文件

foreach (FileSystemInfo f in fi)
{
if (f is DirectoryInfo) //判断是否为文件夹
{
countdir += 1;
Searchfile(f.FullName); //递归调用

}
else
{
countfile += 1;
}
}
label1.Text=string.Format("该目录下一共有{0}个文件夹,有{1}文件",countdir,countfile);



}

private void button1_Click(object sender, EventArgs e)
{
Searchfile(textBox1.Text);

}
}
}



我知道这里的递归调用有点问题,每次递归都会初始countfile 和 countdir这两个量,不知道该怎么改写这段程序?

[解决办法]
放到外面去,累计

读书人网 >C#

热点推荐