简体   繁体   中英

How to read file from the installation folder of app using c#?

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.

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");

Try this function:

using System.Reflection;

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

Then use

File.ReadAllText(MyDirectory() + @"\filename.txt");

短得多

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM