C#读取指定目录下所有文件

根据网上资料整理而得,本来还可以读出所有目录的名字,但是考虑到文件名中包含完整文件路径,故意义不大,就不用读出目录名功能。

主要功能:

1.读取指定目录下含子目录中所有文件。

2.计算文件大小

3.文件含完整路径

4.列表显示到ListBox控件

5.列表写入指定Txt文本文件。



源代码:


using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Collections;

public partial class _Default : System.Web.UI.Page
{

string path = @"\\192.168.1.88\movie\音乐综艺"; //目录名 也可以用相当路径
string filter = "*.*"; //文件类型
int m_numFiles = 0; //文件总数
ArrayList m_pathList = new ArrayList();//包含所有文件路径的数组
string[] files; //所有文件名


protected void Page_Load(object sender, EventArgs e)
{

}

private string[] CreatePathList()
{
if (m_numFiles <= 0)
{
return null;
}

string[] str = new string[m_numFiles];
int index = 0;

try
{
IEnumerator pathIter = m_pathList.GetEnumerator();
while (pathIter.MoveNext())
{
string[] ar = (string[])(pathIter.Current);
IEnumerator fileIter = ar.GetEnumerator();
while (fileIter.MoveNext())
{
str[index] = (string)(fileIter.Current);
++index;
}
}
}
catch (Exception e)
{
Console.Write(e.ToString());
return null;
}

return str;

}

private void ParseDirectory(string path, string p)
{
string[] dirs = Directory.GetDirectories(path);//得到子目录
IEnumerator iter = dirs.GetEnumerator();
while (iter.MoveNext())
{
string str = (string)(iter.Current);
ParseDirectory(str, filter);
}
string[] files = Directory.GetFiles(path, filter);
if (files.Length > 0)
{
foreach (string filename in files)
{

FileInfo inf=new FileInfo(filename);
float value = inf.Length / 1024 /1024;
m_numFiles += files.Length;
m_pathList.Add(files);
ListBox1.Items.Add(filename);
ListBox1.Items.Add("文件大小:"+value.ToString()+"M");
}
}

}

protected void BtGetFileList_Click(object sender, EventArgs e)
{
ParseDirectory(path, "*.*");
files = CreatePathList(); //生成文件名数组
//ListBox1.Items.Add(files.ToString());
if (files == null)
{
throw new Exception(String.Concat("No file found in ", path));
}
}
protected void BtInsrtTxt_Click(object sender, EventArgs e)
{
if (File.Exists("c:\\test.txt") == true)
{
try
{
//label2.Text = "OK";
//File.Delete("c:\\test.txt");
//File.Create("test.txt");
StreamWriter sw = new StreamWriter("c:\\test.txt", true);
for (int i = 0; i < ListBox1.Items.Count; i++)
{
//写入TXT文件
sw.Write(ListBox1.Items[i].ToString() + "\r\n");
}
sw.Close();


}
catch (Exception err)
{
Console.WriteLine(err.ToString());
}
}
else
{
//label2.Text = "error";
}
}
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值