有没有一种方法来查找只是它的名字在C#中的文件? [英] Is there a way to find a file by just its name in C#?

查看:134
本文介绍了有没有一种方法来查找只是它的名字在C#中的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们使用绝对路径或relatvie路径找到我们的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"?

使用绝对百代是不好的,使用相对路径是不够的,因为我们可以通过重命名改变项目结构或移动项目文件夹。如果我们的code可自动搜索当前的工作目录,其子文件夹和搜索系统路径,这将更加灵活。

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.

感谢

推荐答案

试试这个:

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;

这篇关于有没有一种方法来查找只是它的名字在C#中的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆