Reputation: 51
I am creating a c# class (Class.cs) that needs to look for a file(FileINeedToFind.cs) by name from a local directory. The directory is in a different directory from the class file.
folder structure:
Root -> ClassFolder --> Class.cs -> FileFolder --> FileINeedToFind.cs
When I run a test for the class, it always comes back with the test results path.
How can I get the class to get its own local path, and not that of the test results assembly?
Upvotes: 4
Views: 2107
Reputation: 126547
In MSTest, tests are (by default) executed in a different folder than the folder which contains your code, via test deployment. You can configure what gets deployed, but I tend to agree with @Jacob that this isn't something you typically want to do.
However, I differ with @Jacob about how to get the current directory in a test. In MSTest, the right way to do this is with TestContext.DeploymentDirectory.
Upvotes: 3
Reputation: 78850
When a program runs, you should assume that an object has no awareness of the source code that generated it. The code is compiled into an assembly, and that assembly is loaded when you run the program, so the "current" directory by default is the location of the executing assembly.
In short, this is not something you can cleanly do. It's best if your code does not rely on the concept of source-relative directories. It may help you to achieve your goals if you change the build action for the file you're looking for so it's copied to the output directory. Then that file's relative path at runtime should mirror the relative path within your project folder.
To get the path to the executing assembly (the "current" path may be changed by any other executing code, so it's best to not rely on that), use this code:
System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().CodeBase);
Upvotes: 3