熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> .NET編程 >> 正文

C#遍歷所有文件和子目錄

2013-11-13 09:57:53  來源: .NET編程 

  using System;

  using SystemIO;

  class ListAllFilesDemo

  {

  //遍歷所有文件和文件夾查找指定文件並返回該文件的完整路徑

  public static void ListFiles(FileSystemInfo info)

  {

  if (!infoExists) return;

  DirectoryInfo dir = info as DirectoryInfo;

  //不是目錄

  if (dir == null) return;

  FileSystemInfo[] files = dirGetFileSystemInfos();

  for (int i = ; i < filesLength; i++)

  {

  FileInfo file = files[i] as FileInfo;

  //是文件

  if (file != null)

  {

  if (fileNameContains(configincphp))

  {

  ConsoleWriteLine(fileFullName);

  ConsoleReadLine();

  }

  }

  //對於子目錄進行遞歸調用

  else

  ListFiles(files[i]);

  }

  }

  public static void Main()

  {

  ConsoleWrite(請輸入要查詢的目錄: );

  string dir = ConsoleReadLine();

  try

  {

  ListFiles(new DirectoryInfo(dir));

  ConsoleReadLine();

  }

  catch (IOException e)

  {

  ConsoleWriteLine(eMessage);

  }

  }

  }

  網頁形式

  string thePath = //Upload/Star/;

  thePath = ServerMapPath(thePath);//得到文件絕對路徑

  SystemIODirectoryInfo d = new SystemIODirectoryInfo(thePath);

  SystemIODirectoryInfo[] ds = dGetDirectories(** SystemIOSearchOptionTopDirectoryOnly);

  foreach (SystemIODirectoryInfo var in ds)    {

  //路徑全稱

  ResponseWrite(varFullName + <br/>);//遍歷文件夾下面的文件夾

  //僅文件名稱

  ResponseWrite(varName + <br/>);

  }


From:http://tw.wingwit.com/Article/program/net/201311/12136.html
    推薦文章
    Copyright © 2005-2013 電腦知識網 Computer Knowledge   All rights reserved.