ThunD3eR
ThunD3eR

Reputation: 3456

How to get correct path to file in class libary

I have working code for this but I want to optomize it.

I have a MVC Web api and I have tried to build this app with a new structure. I have the project and I have two other projects that are class libraries. In one of these class libraries I have a folder "files" that contains a file that I want to retrive.

Structure:

enter image description here

I have this code:

            char separator = Path.DirectorySeparatorChar;
            string startupPath = AppDomain.CurrentDomain.RelativeSearchPath;
            string[] pathItems = startupPath.Split(separator);
            string projectPath = string.Join(separator.ToString(),
                pathItems.Take(pathItems.Length - 1)) + ".Handler";
            string path = Path.Combine(projectPath, "WebRequestHandlers\\Files" + separator + "Domains.ini");

This Code works.

I dont like the fact that I have to hardcode

".Handler"

to the project path to make this work. My question is, how can I access the class libary from AppDomain, example:

Appdomain.CurrentDomain.SomeMethodToLibary

Upvotes: 1

Views: 1025

Answers (1)

Chris
Chris

Reputation: 2019

Is it just me or what you are doing will not work once you publish your application because you are getting the file path as per your development folder hierarchy ?

What you should do is change the "Build Action" and "Copy To Output Directory" like so: Properties

With those options the file gets copied to the "bin" directory of your main solution (or a sub folder of bin matching where the file is. You should check). The file will be always in the same place and it will get published.

So now the path to your file would be something like this:

string startupPath = AppDomain.CurrentDomain.RelativeSearchPath;
string path = Path.Combine(startupPath, "WebRequestHandlers", "Files", "Domains.ini");

Upvotes: 2

Related Questions