How can I get the application's path in a .NET console application?

后端 未结 27 1408
甜味超标
甜味超标 2020-11-21 11:11

How do I find the application\'s path in a console application?

In Windows Forms, I can use Application.StartupPath to find the current path, but this d

27条回答
  •  感动是毒
    2020-11-21 11:48

    Probably a bit late but this is worth a mention:

    Environment.GetCommandLineArgs()[0];
    

    Or more correctly to get just the directory path:

    System.IO.Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]);
    

    Edit:

    Quite a few people have pointed out that GetCommandLineArgs is not guaranteed to return the program name. See The first word on the command line is the program name only by convention. The article does state that "Although extremely few Windows programs use this quirk (I am not aware of any myself)". So it is possible to 'spoof' GetCommandLineArgs, but we are talking about a console application. Console apps are usually quick and dirty. So this fits in with my KISS philosophy.

提交回复
热议问题