简体   繁体   中英

How to locate a file on multiple directories using C#

I am searching for a file say "abc.txt" on multiple directories. These directories are comma seperated values like

string paths= 'C:/hello,D:/Hello';

How can I search for "abc.txt" using the above comma seperated directories?

Thanks.

You will just need to split the string on the commas then use the DirectoryInfo class to search each directory in turn:

http://msdn.microsoft.com/en-us/library/ms143327.aspx

string paths= 'C:/hello,D:/Hello';
string[] pathList = paths.Split(',');
string searchPattern = "abc.txt";
foreach (string path in pathList)
{
    DirectoryInfo di = new DirectoryInfo(path);
    FileInfo[] files = di.GetFiles(searchPattern, SearchOption.TopDirectoryOnly);
}
  1. You need to split your string from comma:

string paths= 'C:/hello,D:/Hello';

 string[] words = paths.Split(',');
  1. Now you need to get the directory letter from each string token

    foreach (string word in words) {

string directoryName = word.Split(':/')[0];

string searchString = word.Split(':/')[1];

}

Now write your search logic to search in directory.

Split your string based on comma, (I hope you don't have any comma in directory names)

string[] directories = paths.Split(',');
var files = new List<string>();
foreach (string str in directories)
     {
       DirectoryInfo d = new DirectoryInfo(str);
       files.AddRange(Directory.GetFiles(d.FullName, "abc.txt", SearchOption.AllDirectories));
     }

Your files will contain all the abc.txt files in the directories with complete path

I would not suggest using a comma separated list unless you have absolute control over file names (which I assume you don't since you need to to search multiple places).

Keep in mind that file names can contain characters like ',' and ';' which would be an obvious choice for separating the list. If you're in control of creating the list I'd suggest using the pipe char ('|'), it's readable and it can't be part of a file name.

But if you have control over the file names you can simply use split like others have already suggested.

Assuming that there are no commas in file or directory names

string paths= @"C:/hello,D:/Hello";

string multipaths = paths.Split(',');

foreach (string str in multipaths)
{
    string filepath = Path.Combine(str, "abc.txt");

   //Do what you want from these files.
}

your can use split method for that

    string paths= 'C:/hello,D:/Hello';
    string[] words = paths.Split(',');
    foreach (string word in words)
    {
        SearchInDirectory(word)
    }

split Your folders string and search that directory

to search for folder and files you may wanna have a look here http://msdn.microsoft.com/en-us/library/dd997370.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM