- 根据网上资料整理而得,本来还可以读出所有目录的名字,但是考虑到文件名中包含完整文件路径,故意义不大,就不用读出目录名功能。
主要功能:
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";
- }
- }
- }
C#读取所有目录
最新推荐文章于 2020-11-04 10:32:54 发布