5

I am reading a file using File.ReadAllText("filename.txt"). This file is located in very same folder where the .exe file is located (c:/program files/installation folder). But windows app looks into System32 folder for this file by default.

**I don't want to hard code the path of the file.

Jango
  • 5,125
  • 13
  • 55
  • 63

4 Answers4

10

Try this function:

using System.Reflection;

private string MyDirectory()
    {
        return Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
    }

Then use

File.ReadAllText(MyDirectory() + @"\filename.txt");
Longball27
  • 666
  • 1
  • 8
  • 29
9
string path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase );

Gives the directory of the exe. So using that with Path.Combine will give the desired result:

string filenamelocation = System.IO.Path.Combine(path, "filename.txt");
RvdK
  • 19,128
  • 3
  • 59
  • 105
4

A lot shorter

File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "filename.txt");
Bastiaan Linders
  • 1,606
  • 2
  • 11
  • 14
1

So you need directory of your application? In that case, there are some good answers already on SO, for example:

Getting the application's directory from a WPF application

Community
  • 1
  • 1
user218447
  • 649
  • 4
  • 5