Search and return path of given folder name (Windows and Linux)

53 Views Asked by At

I want to get the path of an existing folder SeleniumTestData inside the solution.

Why? My selenium tests should create at start of the test, temporary folder which are being ignored in Git, so each of my colleagues has their own TestData folders for their own TestExecutions on their machine (Like Save/Load Cookies) and dont pull TestData from other colleagues.

The folder where i want to create other folder by code is named SeleniumTestData folder and is inside:

  • ..\source\repos\CoffeeTalk\src\Tests

I cant hardcore the path, as i'm facing here 2 problems:

  • Tests are being ran in Windows and Docker (Linux)
  • Co-Workers are saving the solution in different windows directories

Now i need a general solution which will work in any of these cases.

I already tried: var currentDirectory = new DirectoryInfo(Directory.GetCurrentDirectory()); which returned: D:\source\repos\CoffeeTalk\src\Tests\Web\CoffeeTalk.Client.Selenium.Tests\bin\Debug\net6.0 and then tried to navigate back by executing the codeline currentDirectory?.Parent about 5-6 times. But its then again different in Linux.

Now im looking for a clean way. I suppose the first way i did it was not wrong by getting the CurrentDirectory and navigate back.

I already searched for solutions using stackoverflow, google. Either the solutions are outdated or im not getting the result im expecting.

Here i have the method which creates the folder, but im struggling with the GetFolderPath method.

public static void CreateFolder(string folderName, string newFolderName)
    {
        var folderPath = GetFolderPath(folderName);
        var pathCombined = Path.Combine(folderPath, newFolderName);
        var folderExists = Directory.Exists(pathCombined);
        if (folderExists) return;
        Directory.CreateDirectory(pathCombined);
    }
1

There are 1 best solutions below

2
SNBS On

Directory.GetCurrentDirectory isn't the directory with your executable file. It's something else (I don't know) that by the way depends on the OS. You should use this instead:

using System.Reflection;

// ...

string exeDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);

And then go up the folders hierarchy as you want:

string neededFolder = new DirectoryInfo(exeDirectory).Parent.Parent.Parent.ToString(); // Or more "Parent" calls

As far as I know, it works on different OSs.