How to read file from application installation folder using C #?

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

** I do not want to hardcode the file path.

+3
source share
4 answers

Try this feature:

using System.Reflection;

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

Then use

File.ReadAllText(MyDirectory() + @"\filename.txt");
+5
source
string path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase );

Gives an exe directory. Therefore, using this with Path.Combine will give the desired result:

string filenamelocation = System.IO.Path.Combine(path, "filename.txt");
+8
source

File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "filename.txt");
+3

, ? SO, :

WPF

+1

Source: https://habr.com/ru/post/1743202/


All Articles