Directory Problems

Posted on

Question :

I’m trying to read from an .html file but I can not get the path to this file. I already used Environment.GetCurrentDirectory and Directory.GetCurrentDirectory but did not succeed. Below is the code I’m currently trying, but it tries to retrieve the solution’s execution path.

var foo = File.ReadAllText(@"~/EmailTemplate/email.html");

With this code, I get the following error:

Could not find a part of the path ‘C: …… bin Debug ~ EmailTemplate email.html’.


Answer :

Depending on where you want to get the current directory you should do this:

using System.Console;
using System.IO;
using System.Reflection;

public class Program {
    public static void Main() {
        WriteLine(Path.Combine(Directory.GetCurrentDirectory(), @"EmailTemplate/email.html"));
        WriteLine(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @"EmailTemplate/email.html"));

The first form with Directory.GetCurrentDirectory() takes the current directory that the application is accessing. It may be the same directory as the application or not. You have to see if this is what you want.

If you want to ensure that you get the location where the application is to use the second form that takes the Assembly.GetExecutingAssembly().Location .

If the criterion is another to discover the directory that should be used as a base, you have to find out what the criterion is and choose the method that returns the appropriate information. If neither of these two resolves the problem because the base is different, give me more information in the question so I can put a new option.

Note that Path.Combine is used to transform the two parts of the path in a valid and complete path.

As a curiosity Environment.CurrentDirectory() produces exactly the same as Directory.GetCurrentDirectory() . In fact one calls the other.

See working on dotNetFiddle .


Kleyton, this system variable will pick up the directory where the application is running, so it will display a slightly different behavior in the release version than in debug.

In your case, I see that it is interesting to get the Project / Publication address.

You can access it using:


Try to use the following:

var fi = new System.IO.FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location);
//No exemplo citado presumo que seja um executável
var pastaExe = fi.Directory.FullName;

var caminhoArquivo = System.IO.Path.Combine(pastaExe, "EmailTemplate/email.html");

I believe this will fill your need and you should no longer worry about the file path.


Leave a Reply

Your email address will not be published. Required fields are marked *