【问题标题】:How can I get the name of a sub folder (Thats name will vary) which I need to pass into a hard coded path to run a File.Exists如何获取需要传递到硬编码路径以运行 File.Exists 的子文件夹的名称(名称会有所不同)
【发布时间】:2019-07-17 05:42:25
【问题描述】:

我需要检查某个文件(.config 文件)是否存在于给定的一组子文件夹中,但我不知道这些子文件夹的名称是什么(因为子文件夹是由用户偏好命名的)但是这些子文件夹将仅驻留在给定目录中。

如何将此子文件夹的名称获取到可以使用 File.Exists 检查文件是否存在的路径。

if (File.Exists(@ "D:\TEST\PROJ\Repo\{lastFolderName}\fileserver.config")) {
 MessageBox.Show("File Found");
} else {
 MessageBox.Show("File Not Found");
}

【问题讨论】:

    标签: c# file path


    【解决方案1】:

    你必须像这样尝试

    string path =@ "D:\TEST\PROJ\Repo\";
    DirectoryInfo directory = new DirectoryInfo(path);
    DirectoryInfo[] subDirectories = directory.GetDirectories();
    
    foreach(DirectoryInfo folder in subDirectories)
    {
         string subpath = Path.Combine( @ "D:\TEST\PROJ\Repo\", folder.Name);
         string[] filePaths = Directory.GetFiles(subpath, "fileserver.config");
         if(filePaths.Any())
            Console.WriteLine(subpath);
    }
    

    【讨论】:

    • @Sashitha 是的,如果您必须传递目录名称,那么只需使用此string[] filePaths = Directory.GetFiles(subpath, "fileserver.config"); if(filePaths.Any()) Console.WriteLine(subpath); - 如果对您有用,请接受投票回答
    猜你喜欢
    • 1970-01-01
    • 2011-01-25
    • 1970-01-01
    • 2011-04-13
    • 1970-01-01
    • 2020-12-19
    • 2017-04-20
    • 2016-12-29
    相关资源
    最近更新 更多