开发者

Is there a way to find a file by just its name in C#?

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 abs开发者_运维问答olute 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,


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


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("PATH");
char[] split = new char[] {";"};
foreach (string nextDir in systemPath.Split(split))
{
    if (File.Exists(nextDir + '\\' + target)
    {
        return nextDir;
    }
}

return String.Empty;


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];
    }  
}


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜