【问题标题】:How to read file from the installation folder of app using c#?如何使用c#从应用程序的安装文件夹中读取文件?
【发布时间】:2010-04-28 15:19:18
【问题描述】:

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

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

【问题讨论】:

  • 这个exe是怎么启动的?也许有什么东西会修改当前的工作目录?
  • 它是一个 Windows 服务...一直在运行...只是计划在指定时间调用某些任务。

标签: c# windows windows-services


【解决方案1】:

试试这个功能:

using System.Reflection;

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

然后使用

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

【讨论】:

    【解决方案2】:
    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");
      

      【讨论】:

        【解决方案4】:

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

        Getting the application's directory from a WPF application

        【讨论】:

          猜你喜欢
          • 2016-05-27
          • 1970-01-01
          • 2013-11-12
          • 2013-11-10
          • 2011-01-28
          • 1970-01-01
          • 1970-01-01
          • 2014-09-08
          • 1970-01-01
          相关资源
          最近更新 更多