简体   繁体   English

如何使用c#从app的安装文件夹中读取文件?

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

I am reading a file using File.ReadAllText("filename.txt"). 我正在使用File.ReadAllText(“filename.txt”)读取文件。 This file is located in very same folder where the .exe file is located (c:/program files/installation folder). 此文件位于.exe文件所在的文件夹(c:/ program files / installation folder)中。 But windows app looks into System32 folder for this file by default. 但默认情况下,Windows应用程序会查看此文件的System32文件夹。

**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. 给出了exe的目录。 So using that with Path.Combine will give the desired result: 因此,使用Path.Combine将获得所需的结果:

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: 在这种情况下,SO上已有一些好的答案,例如:

Getting the application's directory from a WPF application 从WPF应用程序获取应用程序的目录

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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