Dynamic Path C #

1

I'm looking for a way to leave the path of a file inside my project dynamically, it's currently like this:

string arquivoImagem = @"D:\Projetos\ProjetoSolution\Projeto.Web\Images\Gerenciador\login\logo.png";

I would like to leave this fixed path as above, how do I make it dynamic?

It is a web application, this path is an image that will be inserted inside a report, it is an image of the application itself so there is no user interference, in case the report uses the path to insert the image in the report that then it becomes a PDF. I would like a way to resolve this because we have problems when another developer opens the project the path does not exist, because the project may be in another location on the machine.

    
asked by anonymous 20.09.2017 / 19:21

3 answers

6

If called in the context of an HTTP call, use the following function to get the root directory of your application:

HttpContext.Current.Server.MapPath("~");

If you do not have the HTTP context, you can still use the second property to get the application path:

HttpRuntime.AppDomainAppPath;

Sources:
HttpServerUtility.MapPath Method (String)
HttpRuntime.AppDomainAppPath Property
Getting current directory in .NET web application

    
20.09.2017 / 19:46
2

In this case you want the physical path, which is a system-level path ("D: \ blabla ...").

Do so (using HttpRuntime.AppDomainAppPath ):

string arquivoImagem = $@"{HttpRuntime.AppDomainAppPath}\Images\Gerenciador\login\logo.png";
    
20.09.2017 / 19:47
1

Brayan, I had a similar problem. I created a configuration table, it contains an ID to distinguish the files and another the path of the file. Then just concatenate the strings:

- dirParam is the information that is in the database.

string dirParam = "..imagens\..\..";
string arquivoImagem = dirParam + "\logo.png";

The case will go back 2 levels in the web page structure and then enter the images folder.

I hope you have helped.

    
25.09.2017 / 13:19