【问题标题】:How to use the function to get location of executable path? [duplicate]如何使用该函数获取可执行路径的位置? [复制]
【发布时间】:2015-12-09 19:33:34
【问题描述】:

我创建了一个Form Application 并尝试获取可执行路径,结果发现:

System.Reflection.Assembly.GetExecutingAssembly().Location;
System.IO.Path.GetDirectoryName;

但是当我输入我的代码时,我遇到了很多错误。

这是我的代码:

namespace inst
{
    public class Program
    {
        System.Reflection.Assembly.GetExecutingAssembly().Location;
        System.IO.Path.GetDirectoryName;

        [STAThread]
        static void Main()
        {
        }
}

它就在我放置的地方吗?我想使用该位置来查找一个文本文件,以便能够更改,如下所示:

private void Form1_Load(object sender, EventArgs e)
{
    this.Text = File.ReadLines(Program.Path)
          .First(x => x.StartsWith("Title=\""))
          .Split(new[] { '=', '"' }, StringSplitOptions.RemoveEmptyEntries)[1];
}

Path 是文件文本的位置。

所以我想获取文件test.txt 所在位置的可执行文件的位置,将位置放在变量中并在form1form2 中使用该变量,就我而言

【问题讨论】:

    标签: c#


    【解决方案1】:

    只需将System.Reflection.Assembly.GetExecutingAssembly().Location; 行放在Form1_Load 方法中即可。并使用它返回的内容。顺便说一句,如果您尝试访问的文件与程序集位于同一目录中,则无需获取路径。这些路径是相对于执行程序集的路径。

    同样在 WinForm 应用程序中最好使用Application.StartupPath 来获取路径。

    不允许在方法之外有代码,除了声明之外,就像你的方式一样:

    System.Reflection.Assembly.GetExecutingAssembly().Location;
    System.IO.Path.GetDirectoryName;
    

    而且编译器也不喜欢它根本不是一个语句。你应该做类似var value = Something; 而不仅仅是Something;

    【讨论】:

      【解决方案2】:

      只需声明一个字符串

      private string Path
          {
              get { return Assembly.GetExecutingAssembly().Location.ToString();}
          }
      

      然后在你想要的地方使用它

      编辑:目录路径是这样的:

      private string Path
      {
          get {return AppDomain.CurrentDomain.BaseDirectory.ToString();}
      }
      

      您的代码将是

      namespace inst
      {
          public class Program
          {
              private string Path
              {
                  get {return AppDomain.CurrentDomain.BaseDirectory.ToString();}
              }
      
              [STAThread]
              static void Main()
              {
              }
      }
      

      和你的功能(谁在同一个类程序)

      private void Form1_Load(object sender, EventArgs e)
      {
          this.Text = File.ReadLines(Path)//here the string with the directory path
                .First(x => x.StartsWith("Title=\""))
                .Split(new[] { '=', '"' }, StringSplitOptions.RemoveEmptyEntries)[1];
      }
      

      如果您希望变量 Path 可以在所有其他类中访问,您可以添加一个静态类并将字符串声明添加为 public,您可以像这样在任何地方使用它 yourStaticClassName.Path

      【讨论】:

      • 我把它放在类 Program 中,因为我想成为一个全局变量,但是当我运行它时,我有 12 个错误
      • 我只想有目录名,没有可执行文件名?
      • 我根据您需要的目录路径编辑我的帖子。希望对您有所帮助
      • 并附上文件名我有下一行: var link = File.ReadLines(Program.Path + "\test.txt");但是当我运行时出现 3 个错误
      • 这些错误是什么?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-24
      • 1970-01-01
      • 2012-10-20
      • 2014-09-21
      • 1970-01-01
      • 1970-01-01
      • 2019-09-22
      相关资源
      最近更新 更多