windows 如何使用c#从应用程序的安装文件夹中读取文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2730800/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 14:22:07  来源:igfitidea点击:

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

c#windowswindows-services

提问by Jango

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.

我正在使用 File.ReadAllText("filename.txt") 读取文件。此文件位于 .exe 文件所在的同一文件夹中(c:/program files/installation 文件夹)。但默认情况下,Windows 应用会查看此文件的 System32 文件夹。

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

**我不想硬编码文件的路径。

回答by RvdK

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:

给出exe的目录。因此,将其与 Path.Combine 一起使用将给出所需的结果:

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

回答by Longball27

Try this function:

试试这个功能:

using System.Reflection;

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

Then use

然后使用

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

回答by Bastiaan Linders

A lot shorter

短了很多

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

回答by user218447

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

所以你需要你的应用程序目录?在这种情况下,SO 上已经有一些很好的答案,例如:

Getting the application's directory from a WPF application

从 WPF 应用程序获取应用程序的目录