views:

86

answers:

3

i have filename according to this file name. i need to find file's path. how to find file's path according to filename? i need to find file's path according to file name sample code:

string path=      System.IO.Directory.GetDirectories(@"c:\", "kategori",System.IO.SearchOption.AllDirectories).First();

But i need :

string path=      System.IO.Directory.GetDirectories(@"anyFolder", "kategori",System.IO.SearchOption.AllDirectories).First();

i need below


Main()
{
string path = PathFinder("Afilename")
}

output: C:\myFiles\AfileName

string PathFinder(string fileName)
{
..................
.................
........
.......
....
..
.
}
+2  A: 

Probably a function like this could work for you:

public static String SearchFileRecursive(String baseFolderPath, String fileName)
    {
        // Returns, if found, the full path of the file; otherwise returns null.
        var response = Path.Combine(baseFolderPath, fileName);
        if (File.Exists(response))
        {
            return response;
        }

        // Recursion.
        var directories = Directory.GetDirectories(baseFolderPath);
        for (var i = 0; i < directories.Length; i++)
        {
            response = SearchFileRecursive(directories[i], fileName);
            if (response != null) return response;
        }

        // { file was not found }

        return null;
    }
Erik Burigo
i give a clearance above codes....
Phsika
@Sam: Thank you, you are right (I have no rights to start commenting a question). I opted for changing this comment-answer into a true answer.
Erik Burigo
+2  A: 

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

jgauffin
+1  A: 

I'd like more the LINQish way:

public IEnumerable<FileInfo> FindFile(string fileName)
{
    if (String.IsNullOrEmpty(fileName))
        throw new ArgumentException("fileName");

    foreach (var drive in Directory.GetLogicalDrives())
    {
        using (var e = FindFile(fileName, drive).GetEnumerator())
            while (e.MoveNext())
                yield return e.Current;
    }
}

public IEnumerable<FileInfo> FindFile(string fileName, string folderName)
{
    if(String.IsNullOrEmpty(fileName))
        throw new ArgumentException("fileName");
    if(String.IsNullOrEmpty(fileName))
        throw new ArgumentException("folderName");

    var matchingFiles = Directory.GetFiles(folderName)
                                 .Where(file => Path.GetFileName(file) == fileName)
                                 .Select(file => new FileInfo(file));

    using (var e = matchingFiles.GetEnumerator())
        while (e.MoveNext())
            yield return e.Current;

    foreach (var directory in Directory.GetDirectories(folderName))
    {
        using (var e = FindFile(fileName, directory).GetEnumerator())
            while (e.MoveNext())
                yield return e.Current;
    }
}

which can be used by:

foreach (var file in FindFile("myFile.ext"))
{
    Console.WriteLine("Name: " + file.FullName);
}
Oliver