locked
Search a file

    Întrebare

  • How to search a file in all harddisks which computer have and how to search even in external harddisk(Which is portable)  using C#.Net

    please any one guide me with a piece of code

    11 martie 2012 04:30

Răspunsuri

  • Hi SKp03,

    Welcome to the MSDN forum.

    Here is an integrated code sample I write for you to test, please check it out:

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    
    namespace ConsoleApplicationTemp
    {
        internal class Program
        {
            private static void SearchForFiles(string path, string pattern)
            {
                foreach (string file in Directory.GetFiles(path, pattern))
                {
                    Console.WriteLine(file);
                }
                foreach(string dir in Directory.GetDirectories(path))
                {
                    try
                    {
                        SearchForFiles(dir,pattern);
                    }
                    catch(Exception ex)
                    {
                        Console.WriteLine("Cannot access " + dir);//You can comment this line, if too many lines are displayed.
                    }
                }
            }
    
            static void Main(string[] args)
            {
                foreach(DriveInfo drive in DriveInfo.GetDrives())
                {
                    string DriveName = drive.Name;
                    SearchForFiles(DriveName, "123.txt");
                    Console.WriteLine("Searching over.");
                }
            }
        }
    }
    

    First, I use DriveInfo.GetDrives() to retrieve the drive names of all logical drives on a computer. Please refer to this page: http://msdn.microsoft.com/en-us/library/system.io.driveinfo.getdrives.aspx

    Then, I use a foreach statement to iterate all the drives. In SearchForFiles method, I use the recursion to iterate all the directories and its sub directories on a drive. In the process of recursion, I cast Directory.GetFiles to return the names of files (including their paths) in the specified directory. Please refer to this page: http://msdn.microsoft.com/en-us/library/07wt70x2.aspx

    In addition, the Directory.GetDirectories method is used to get the names of subdirectories (including their paths) in the specified directory. You can refer to this page:
    http://msdn.microsoft.com/en-us/library/c1sez4sc.aspx
    If you have any other problems, please feel free to let me know.

    Best Regards,


    Alexander Sun [MSFT]
    MSDN Community Support | Feedback to us

    13 martie 2012 07:28

Toate mesajele

  • You need to create a recursive search method for this purpose (pass the drive as root folder to this method)

    link: 

    http://support.microsoft.com/kb/303974

    + use an enumerator to list all drives/external hard disks

    ManagementClass diskClass = new ManagementClass("Win32_LogicalDisk");
    
    ManagementObjectCollection disks = diskClass.GetInstances();
    
    foreach (ManagementObject disk in disks) {
    
    Console.WriteLine("Disk = " + disk["deviceid"]);
    
    }
    

    or

    Use Operating System build in features.


    Resolving n Evolving in C# (http://jeanpaulva.com)

    11 martie 2012 05:46
  • using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    
    namespace ConsoleApplication133
    {
    	internal class Program
    	{
    		private static void Main(string[] args)
    		{
    			var file = "New Text Document.txt";
    			var foundDirs = new List<DirectoryInfo>();
    			Action<DirectoryInfo> lookForFile = null;
    			lookForFile = delegate(DirectoryInfo dir)
    			{
    				FileInfo[] files;
    				try
    				{
    					files = dir.GetFiles();
    				}
    				catch
    				{
    					return;
    				}
    				foreach (var f in files)
    					if (string.Compare(file, f.Name, true) == 0)
    						foundDirs.Add(dir);
    				foreach (var directory in dir.GetDirectories())
    					lookForFile(directory);
    			};
    			foreach (var drive in DriveInfo.GetDrives().Where(drv => drv.IsReady))
    			{
    				Console.WriteLine("Looking in {0}", drive.Name);
    				foreach (var root in drive.RootDirectory.GetDirectories())
    				{
    					FileInfo[] files;
    					try
    					{
    						files = root.GetFiles();
    					}
    					catch
    					{
    						continue;
    					}
    					foreach (var f in files)
    						if (string.Compare(file, f.Name, true) == 0)
    						{
    							foundDirs.Add(root);
    							Console.WriteLine("Found in {0}", root.FullName);
    						}
    					foreach (var directory in root.GetDirectories())
    						lookForFile(directory);
    				}
    			}
    		}
    	}
    }

    Check this code out.

    Mohammad - C# Lover

    11 martie 2012 11:09
  • If this is an ongoing process then you might consider lucene.net to index the files first and then search the index.    To read files you use tika (not sure of spelling) to rip the data out of various file types which may help you even if you are doing this once.

    Ta Ken

    11 martie 2012 22:18
  • waratah

    as i am new to the C# can you just help me out with a code please

    12 martie 2012 04:42
  • Hi SKp03,

    Welcome to the MSDN forum.

    Here is an integrated code sample I write for you to test, please check it out:

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    
    namespace ConsoleApplicationTemp
    {
        internal class Program
        {
            private static void SearchForFiles(string path, string pattern)
            {
                foreach (string file in Directory.GetFiles(path, pattern))
                {
                    Console.WriteLine(file);
                }
                foreach(string dir in Directory.GetDirectories(path))
                {
                    try
                    {
                        SearchForFiles(dir,pattern);
                    }
                    catch(Exception ex)
                    {
                        Console.WriteLine("Cannot access " + dir);//You can comment this line, if too many lines are displayed.
                    }
                }
            }
    
            static void Main(string[] args)
            {
                foreach(DriveInfo drive in DriveInfo.GetDrives())
                {
                    string DriveName = drive.Name;
                    SearchForFiles(DriveName, "123.txt");
                    Console.WriteLine("Searching over.");
                }
            }
        }
    }
    

    First, I use DriveInfo.GetDrives() to retrieve the drive names of all logical drives on a computer. Please refer to this page: http://msdn.microsoft.com/en-us/library/system.io.driveinfo.getdrives.aspx

    Then, I use a foreach statement to iterate all the drives. In SearchForFiles method, I use the recursion to iterate all the directories and its sub directories on a drive. In the process of recursion, I cast Directory.GetFiles to return the names of files (including their paths) in the specified directory. Please refer to this page: http://msdn.microsoft.com/en-us/library/07wt70x2.aspx

    In addition, the Directory.GetDirectories method is used to get the names of subdirectories (including their paths) in the specified directory. You can refer to this page:
    http://msdn.microsoft.com/en-us/library/c1sez4sc.aspx
    If you have any other problems, please feel free to let me know.

    Best Regards,


    Alexander Sun [MSFT]
    MSDN Community Support | Feedback to us

    13 martie 2012 07:28
  • Hello  Alexander Sun 

    ya your code is short and sweet , ya really it is working

    but

    how can i search a file in and only external hard disk (which is portable)

    please let me fast 

    please

    thank you

    13 martie 2012 08:59
  • Did you check out my source, my friend? this snippet gives you all the drives connected to your PC, which are ready to use:
    (var drive in DriveInfo.GetDrives().Where(drv => drv.IsReady)

    you can paste it as foreach argument (as I used it in my code)

    Mohammad - C# Lover

    17 martie 2012 08:38
  • Assalam mu alai kum

    mostafa bhai can i get your personal mail ID so that, if i have a doubt i'll directly mail you

    17 martie 2012 08:53
  • Hi Skp03,

    If you start this application after you inject the external hard disk, it is not possible to determine which hard drive is the external hard drive. Since the type of external hard drive is Fixed which is the same as the local logic hard drive (unlike the USB device whose type is Removable), we cannot distinguish external hard drive from all hard drives.

    For DriveInfo.IsReady Property, it gets a value indicating whether a drive is ready. You can refer to this page: http://msdn.microsoft.com/en-us/library/system.io.driveinfo.isready.aspx

    In the following sample in preceding page, the result all drives including removable device, fixed devices and CD-ROM device. Thus, it cannot identify the external hard drive.

    In addition, you also can record the original disks list before connecting the external harddisk, and compare with the list after connecting, via the DriveInfo.GetDrives() method. It means you are required to run application first before you inject the external hard disk.

    If you have any other problems, please feel free to let me know.

    Best Regards,


    Alexander Sun [MSFT]
    MSDN Community Support | Feedback to us

    19 martie 2012 08:25