6

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,375
  • 14
  • 57
  • 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
  • 676
  • 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,580
  • 4
  • 64
  • 107
4

A lot shorter

File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "filename.txt");
Bastiaan Linders
  • 1,861
  • 2
  • 13
  • 15
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
  • 659
  • 5
  • 5