- .net创建XML 写入集合数据
- seo学习之入门宝典
- nofollow属性的介绍和使用1
- PHP中str_replace()函数介绍
- 石家庄飞讯网站Session失效太快的解决方法
- 虚拟主机中“使用独立的应用程序池”是什么意思?
- .net先运行接口还是先运行实现类
- 为什么老出现XXX函数未定义错误?
- Window.ShowModalDialog使用手册
- 企业网站优化不要盲目选择关键词
邮箱:
手机:15383239821
asp.net遍历文件夹目录和文件实现程序
在asp.net中经遍历文件夹需要利用文件对象GetFileSystemInfos() GetDirectories() FileSystemInfo()来实现我们的功能,下面我找了三个目录遍历的实例分享给大家。
方法一
代码如下
private void forFileLength(DirectoryInfo directory)
{
DirectoryInfo[] directorys = directory.GetDirectories();
FileInfo[] files;
foreach (DirectoryInfo di in directorys)
{
forFileLength(di);
}
files = directory.GetFiles();
foreach(FileInfo file in files)
{
string temp = file.DirectoryName.ToString(); // 当前路径件
string name = file.Name; // name 文件名
}
}
方法二
(1)新建一个网站,其中默认Web窗体为Default.aspx。
(2)在Default.aspx中添加一个TextBox控件、一个Button控件和一个Lable控件,分别用来输入遍历文件夹的路径、开始遍历文件夹并获取文件数量、显示遍历文件的数量。
(3)单击【获取文件数量】按钮来获取指定文件夹下的文件数量,主要通过调用自定义方法GetAllFiles实现。在【获取文件数量】按钮的Click事件下添加代码如下:
代码如下 复制代码
int j = 0;
protected void Button1_Click(object sender, EventArgs e)
{
DirectoryInfo dir = new DirectoryInfo(TextBox1.Text.ToString());
Label1.Text = GetAllFiles(dir).ToString();
}
GetAllFiles方法为自定义方法,实现遍历整个文件夹文件的方法。代码如下:
代码如下
public int GetAllFiles(DirectoryInfo dir)
{
FileSystemInfo[] fileinfo = dir.GetFileSystemInfos();
foreach (FileSystemInfo i in fileinfo)
{
if (i is DirectoryInfo)
{
GetAllFiles((DirectoryInfo)i);
}
else
{
j++;
}
}
return j;
}
说明:首先要导入命名空间System.IO,GetAllFiles方法可以识别文件夹中的隐藏文件,遍历出来的文件数量是文件夹中包括隐藏文件在内的所有文件的数量
方法三
代码如下 复制代码
protected void Page_Load(object sender, EventArgs e)
{
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(Server.MapPath(“~/”));
TreeView treeView1 = new TreeView();
TreeNode nodeMain = OutPutNodes(dir, null);
treeView1.Nodes.Add(nodeMain);
this.form1.Controls.Add(treeView1);
}
private TreeNode OutPutNodes(System.IO.DirectoryInfo dir, TreeNode parentNode)
{
if (dir == null)
return null;
TreeNode dirNode = new TreeNode(dir.Name);
System.IO.DirectoryInfo[] subDirs = dir.GetDirectories();
for (int i = 0; i < subDirs.Length; i++)
{
OutPutNodes(subDirs[i], dirNode);
}
System.IO.FileInfo[] files = dir.GetFiles();
for (int i = 0; i < files.Length; i++)
{
dirNode.ChildNodes.Add(new TreeNode(files[i].Name));
}
if (parentNode == null)
{
return dirNode;
}
else
{
parentNode.ChildNodes.Add(dirNode);
return parentNode;
}
}
总结
历一个文件夹中的文件,需要用到DirectoryInfo类中的一个重要的方法GetFileSystemInfos(),此方法返回指定的是与搜索条件相匹配的文件和子目录的强类型 FileSystemInfo对象的数组。
-
2024-09-18什么是社区团购系统?
-
2024-01-14IReadOnlyCollection
与IReadOnlyList -
2010-07-20提高淘宝排名技巧
-
2010-10-02SQL语句大全
-
2012-06-30nofollow属性的介绍和使用1
-
2013-10-30Request、Request.Form和Request.QueryString的区别
