Lists files in the current working directory
/* C# Programming Tips & Techniques by Charles Wright, Kris Jamsa Publisher: Osborne/McGraw-Hill (December 28, 2001) ISBN: 0072193794 */ // ShowDir.cs -- Changes the current working directory and then lists //the files in the directory. // //Compile this program with the following command line: // C:>csc ShowDir.cs using System; using System.IO; namespace nsStreams { public class ShowDir { static public void Main (string [] args) { if (args.Length > 0) { // Build the directory name from the arguments (a directory name may // contain spaces). string DirName = ""; foreach (string str in args) { DirName += str; DirName += " "; } // Strip any leading or trailing spaces from the directory name DirName = DirName.Trim (); // Check whether the directory exists //if (!Directory.Exists(DirName)) //{ // Console.WriteLine ("No such directory: " + DirName); // return; //} // Set the current working directory try { Directory.SetCurrentDirectory (DirName); } catch (UnauthorizedAccessException) { Console.WriteLine ("Not authorized to access " + DirName); return; } catch (FileNotFoundException) { Console.WriteLine ("No such directory: " + DirName); return; } } // List the files in the selected directory string [] files = Directory.GetFiles ("."); foreach (string str in files) { int index = str.LastIndexOf ("\\"); Console.WriteLine (str.Substring (index + 1)); } } } }
Filed Under: C# Streams Examples