简体   繁体   中英

string.IsNullOrEmpty to combine another directory

I want ask to find directory name it (folder1) to combine. But if directory not exist, i want to find another directory name it (folder2) to combine. What should i put to it? Here the code:

    public static string DataDirectory
    {

        get
        {

            if (string.IsNullOrEmpty(Directory))
                return null;

            return Path.Combine(Directory, "Data/folder1");

        }

    }

Thanks.

Directory.Exists should work fine

public static string DataDirectory
{

    get
    {

        if (string.IsNullOrEmpty(Directory))
            return null;

        // Use Path.Combine just one time 
        string firstFolder = Path.Combine(Directory, "Data/folder1"); 
        if(Directory.Exists(firstFolder)
            return Path.Combine(firstFolder);
        else
            return Path.Combine(Directory, "Data/folder2");
    }

}

you could also do something like this to first check if there are any directories, then use linq to order the directories and select the first element.

public static string GetDataDirectory(string root)
{
    var directoryList = Directory.GetDirectories(root);
    if (!directoryList.Any())
        return null;

    directoryList = directoryList.OrderBy(dir => dir).ToArray();
    return directoryList.First();
}    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM