2010-04-28 110 views
3

我正在使用File.ReadAllText(“filename.txt”)读取文件。该文件位于.exe文件所在的非常相同的文件夹中(c:/ program files/installation文件夹)。但Windows应用程序默认查看System32文件夹中的这个文件。如何使用c#从应用程序的安装文件夹读取文件?

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

+0

这个'exe'是如何启动的?也许有什么修改当前的工作目录? – 2010-04-28 15:22:34

+0

它的Windows服务...总是运行....只是计划根据指定的时间调用某些任务。 – Jango 2010-04-28 15:27:31

回答

5

试试这个功能:

using System.Reflection; 

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

然后使用

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

给出exe的目录。 因此,使用与Path.Combine将得到期望的结果:

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

短了很多

File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "filename.txt"); 
相关问题