Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

reading all files in a directory and storing their name in an array

Status
Not open for further replies.

yahoo182

Programmer
Jul 5, 2005
70
CA
Hi there,
What I am trying to do now is to read in a directory that contains about ~100 xml files and store their name into an dynamic ArrayList collection.
Does anyone have a clue how I can do this is C# ?

I am quite a newbie to this language.

Thanks !
 
All found it :)
Just in case you had to do the same thing.


Code:
using System;
using System.IO;
using System.Text;
class DirCommand {
  static void Main( ) {
    long numFiles=0, numDirs=0, totalBytes=0;
    string currentDir = Directory.GetCurrentDirectory( );
    DirectoryInfo currentDirInfo = new DirectoryInfo(currentDir);
    StringBuilder sb = new StringBuilder( );
    sb.AppendFormat(" Directory of {0}\n\n", currentDirInfo.FullName);
    DirectoryInfo rootDirInfo = currentDirInfo.Root;
    if (rootDirInfo != null) {
      sb.AppendFormat("{0:dd/MM/yyyy  hh:mm tt}    <DIR>          .\n",
                      rootDirInfo.LastWriteTime);
      numDirs++;
    }
    DirectoryInfo parentDirInfo = currentDirInfo.Parent;
    if (parentDirInfo != null) {
      sb.AppendFormat("{0:dd/MM/yyyy  hh:mm tt}    <DIR>          ..\n",
                      parentDirInfo.LastWriteTime);
      numDirs++;
    }
    FileSystemInfo[ ] fsis = currentDirInfo.GetFileSystemInfos( );
    foreach (FileSystemInfo fsi in fsis) {
      FileInfo fi = fsi as FileInfo;
      if (fi != null) {
        sb.AppendFormat("{0:dd/MM/yyyy  hh:mm tt}    {1,14:N0} {2}\n",
                        fi.LastWriteTime, fi.Length, fi.Name);
        numFiles++;
        totalBytes += fi.Length;
      }
      DirectoryInfo di = fsi as DirectoryInfo;
      if (di != null) {
        sb.AppendFormat("{0:dd/MM/yyyy  hh:mm tt}    <DIR>         {1}\n",    
                        di.LastWriteTime, di.Name);
        numDirs++;
      }
    }
    sb.AppendFormat("{0,16:G} File(s) {1,14:N0} bytes\n", numFiles,
                    totalBytes);
    sb.AppendFormat("{0,16:G} Dir(s)\n", numDirs);
    Console.WriteLine(sb.ToString( ));
  }
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top