tags:

views:

152

answers:

5

We use absolut path or relatvie path to find a file in our C# application right now. Is there a way to find the file just by its name if the file is under the currect working directory or under one of the "paths"?

Use absolute pathe is not good and use relative path is not good enough because we may change project structure by rename or move project folders. If we our code can automatically search current working directory, its subfolders and search system path, that will be more flexible.

thanks,

+3  A: 

You can easily build a recursive function to do this for you. Look at Directory.GetDirectories and Directory.GetFiles, both under System.IO

Dan at Demand
There's a sample on MSDN showing you exactly how to do this: http://msdn.microsoft.com/en-us/library/bb513869.aspx
Richard Cook
A: 

You can get the exe's directory using

Path.GetDirectoryName(Application.ExecutablePath);

Example Code: http://www.csharp-examples.net/get-application-directory/

And then, you can search the folders from there using recursion. This is a good article on recursive searching for files: http://support.microsoft.com/kb/303974

J J
+1  A: 

You could call Directory.GetFiles for each root folder in which you want to search for the file. the parameter searchOption allow you to specify whether the search operation look in all subdirectories or only the directory specified. E.g:

public string GetFileName(string[] folders,string fileName) {
    string[] filePaths;
    foreach(var folder in folders) {
        filePaths=Directory.GetFiles(folder,fileName,SearchOption.AllDirectories)
        if (filePaths.Lenght>0)
            return filePaths[0];
    }  
}
Andrea Parodi
+1  A: 

Try this:

Directory.EnumerateFiles(pathInWhichToSearch, fileNameToFind, SearchOption.AllDirectories);

And, you need to use:

using System.IO;

on top of your class.

This searches all subdirectories of pathInWhichToSearch for a file with name fileNameToFind (it can be a pattern too - like *.txt) and returns result as IEnumerable<string> with full paths of found files.

Ivan Ferić
are you using .net 4? there is no EnumerateFiles in my .net 3.5.
5YrsLaterDBA
Yes, it's in .NET Framework 4.0
Ivan Ferić
A: 

Try this:

string target = "yourFilenameToMatch";
string current = Directory.GetCurrentDirectory();

// 1. check subtree from current directory
matches=Directory.GetFiles(current, target, SearchOption.AllDirectories);
if (matches.Length>0)
    return matches[0];

// 2. check system path
string systemPath = Environment.GetEnvironmentVariable("SYSTEMROOT");
char[] split = new char[] {";"};
foreach (string nextDir in systemPath.Split(split))
{
    if (File.Exists(nextDir + '\\' + target)
    {
        return nextDir;
    }
}

return String.Empty;
Steve Townsend