CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5
  1. #1
    Join Date
    Feb 2008
    Posts
    108

    Listing of files using C#

    I recently downloaded the Visual Studio 2008 for C#. I like the ease of program development. I started off with Console Applications to learn C#. In C/C++ you can get a listing of all the files of a certain type by using the following command:
    Code:
    system("dir/s /b *.txt >text.dat");
    I could not find a similar command in C#, so I wrote a recursive function to traverse all the subdirectories of a particular directory and write a list of the files into a text file that match the file extension passed into the function. The FileStream is passed into the function after being created in the 'Main' part of the program and closed there after the function returns. The function works fine as intended, but my question is this, "Is there a less cumbersome method in C# to use which will accomplish what the above mentioned system command in 'C' does?
    Code:
            static void WriteDirInformation(string FullDirPath, FileStream fs, string File_ext)
            {
                System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(@FullDirPath);
                string fullPath = Path.GetFullPath(@FullDirPath);
                fullPath += "\\";
    
                Console.WriteLine("Files in {0}", FullDirPath);
                foreach (System.IO.FileInfo file in dir.GetFiles(File_ext))
                {
                    string fullFilePath = fullPath + file.Name;
                    Console.WriteLine("{0}", fullFilePath);
                    fullFilePath += "\n";
                    byte[] info = new UTF8Encoding(true).GetBytes(fullFilePath);
                    fs.Write(info, 0, info.Length);
                }
                DirectoryInfo[] diArr = dir.GetDirectories();
    
                // Display the names of the directories.
                if (diArr.Length > 0)
                {
                    foreach (DirectoryInfo dri in diArr)
                    {
                        string fullDirPath = fullPath + dri.Name;
                        Console.WriteLine(fullDirPath);
                        WriteDirInformation(fullDirPath, fs, File_ext);
                    }
                }
            }

  2. #2
    Join Date
    May 2007
    Posts
    1,546

    Re: Listing of files using C#

    Code:
    		public static void Main(string[] args)
    		{
    			List<FileInfo> files = new List<FileInfo>();
    			GetAllFile(@"C:\MyFiles", "*.txt",  files);
    			using (StreamWriter w = new StreamWriter(@"contents.txt"))
    				files.ForEach(delegate (FileInfo f) { w.WriteLine(f.Name); });
    		}
    		
    		public static GetAllFiles(string path, string filter, List<FileInfo> files)
    		{
    
    			foreach (string dir in Directory.GetDirectories(path))
    				GetAllFiles (Path.Combine(path, dir));
    			
    			foreach (string file in Directory.GetFiles(path, filter))
    				files.Add(new FileInfo(Path.Combine(path, file)));
    		}
    	}
    Is that any easier for ya?
    www.monotorrent.com For all your .NET bittorrent needs

    NOTE: My code snippets are just snippets. They demonstrate an idea which can be adapted by you to solve your problem. They are not 100% complete and fully functional solutions equipped with error handling.

  3. #3
    Join Date
    Jun 2004
    Location
    Kashmir, India
    Posts
    6,808

    Re: Listing of files using C#

    In case you just want to take it to single line then you can use Process Class's Start method like this
    Code:
                System.Diagnostics.Process.Start(@"C:\Windows\system32\cmd.exe",@"/c dir /s/b C:\MyFolders > C:\files.dat");

  4. #4
    Join Date
    Feb 2008
    Posts
    108

    Re: Listing of files using C#

    Thanks Shuja Ali and Mutant_Fruit for your replies. I especially like the one-line command rather then writing a lot of code. I tried your code, Shuja Ali, and it works (just changed the target directory from C:\MyFolders to one of my existing directories).
    Mutant_Fruit, I liked your solution, also, but it contained typos and only wrote the filenames without the path to the files to "contents.txt". I fixed the typos and changed the target directory and now your solution works as I intended. Here is the
    Code:
           public static void Main(string[] args)
    		{
    			List<FileInfo> files = new List<FileInfo>();
    			GetAllFiles(@"C:\tmp1\", "*.txt",  files);
    			using (StreamWriter w = new StreamWriter(@"contents.txt"))
    				files.ForEach(delegate (FileInfo f) 
                    		{ 
                        			w.WriteLine(f.DirectoryName + "\\" + f.Name); 
                    		}
                		);
    		}
    		
    		public static void GetAllFiles(string path, string filter, List<FileInfo> files)
    		{
    
    			foreach (string dir in Directory.GetDirectories(path))
                    GetAllFiles(Path.Combine(path, dir), filter, files);
    			
    			foreach (string file in Directory.GetFiles(path, filter))
    				files.Add(new FileInfo(Path.Combine(path, file)));
    		}

  5. #5
    Join Date
    May 2007
    Posts
    1,546

    Re: Listing of files using C#

    Aye, i never compiled it, the idea should be clear though

    The benefit of doing it entirely with .NET code is that you can process the list of files after you generate em. You can sort them, modify them, remove duplicates, whatever. You lose that ability by calling the command prompt. Also, calling the command prompt isn't portable If you want to run your app on different operating systems, then you can't do it that way.

    Glad ya got it working anyway.
    www.monotorrent.com For all your .NET bittorrent needs

    NOTE: My code snippets are just snippets. They demonstrate an idea which can be adapted by you to solve your problem. They are not 100% complete and fully functional solutions equipped with error handling.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured