C# 如何获取应用程序的路径(没有app.exe)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/881251/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the path of app(without app.exe)?
提问by Chilly Zhong
I want to get the path of my app like: "\\ProgramFiles\\myApp", I try to use the following code:
我想获取我的应用程序的路径,例如:“\\ProgramFiles\\myApp”,我尝试使用以下代码:
string path = System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase;
But it returns a path which has "\\myapp.exe" at the end.
但它返回的路径末尾有“\\myapp.exe”。
I also tried:
我也试过:
string path = System.IO.Directory.GetCurrentDirectory();
But it throws an “NotSupportedException”.
但它会抛出“NotSupportedException”。
Is there any way to get a path without .exe at the end?
有没有办法在最后获得没有 .exe 的路径?
采纳答案by Dan Bystr?m
path = System.IO.Path.GetDirectoryName( path );
回答by Fredrik M?rk
Application.StartupPath
should do that for you.
Application.StartupPath
应该为你做那件事。
Update: from you edit I see that you are running on Compact Framework. Then Application.StartupPath will not work. This is the construct that I usually use then:
更新:从你的编辑中我看到你在 Compact Framework 上运行。那么 Application.StartupPath 将不起作用。这是我通常使用的构造:
private static string GetApplicationPath()
{
return System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
}
回答by okutane
You can use Path.GetDirectoryName(string) method passing your original path string as parameter for this. What problem are you trying to solve? Maybe you really need something like working directory?
您可以使用 Path.GetDirectoryName(string) 方法将原始路径字符串作为参数传递。你想解决什么问题?也许你真的需要像工作目录这样的东西?
回答by JP Alioto
Path.GetFileNameWithoutExtension(path);
回答by amrtn
What about using a FileInfo object to extract the directory name?
使用 FileInfo 对象提取目录名称怎么样?
In Vb.Net:
在 Vb.Net 中:
fi = New FileInfo(System.Reflection.Assembly.GetExecutingAssembly.Location)
path = fi.DirectoryName
回答by NileshChauhan
If its an exe as in your case use:
如果它是您的情况下的 exe,请使用:
// Summary:
// Gets the path for the executable file that started the
// application, not including the executable name.
Application.StartupPath
回答by Chris
More simple than the rest:
比其他的更简单:
using System.IO;
using System.Reflection;
...
var path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)