开发者

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

开发者 https://www.devze.com 2022-12-29 00:26 出处:网络
I am reading a file using File.ReadAllText(\"filename.txt\"). This file is located in very same folder where the .exe file is locate开发者_开发问答d (c:/program files/installation folder). But windows

I am reading a file using File.ReadAllText("filename.txt"). This file is located in very same folder where the .exe file is locate开发者_开发问答d (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.


Try this function:

using System.Reflection;

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

Then use

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


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


A lot shorter

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号