可能的重复:
如何找出我的控制台应用程序在 C# 中运行的目录? https://stackoverflow.com/questions/97312/how-do-i-find-out-what-directory-my-console-app-is-running-in-with-c
如何获取运行程序的控制台的当前工作目录,以便我可以解析作为程序参数传递的相对路径?
假设我把我的程序放在这里:c:\tools\program.exe
但我从不同的地方调用它。假设我在这里:C:\Users\Me\Documents\
我运行这个命令program.exe --src=somefile.txt --dest=subdir\otherfile.txt
Environment.CurrentDirectory
and System.Reflection.Assembly.GetExecutingAssembly().Location
将返回c:\tools
但我希望能够解决somefile.txt
and subdir\oterfile.txt
相对于的路径C:\Users\Me\Documents\
.
======更新======
感谢您的帮助。看起来Environment.CurrentDirectory
按预期工作。事实证明,就我而言,问题是由 Xenocode 的 Postbuild 工具(现在称为 Spoon Virtual Application Studio)引起的,我偶尔会使用该工具将所有程序文件(包括 dll、配置等)“打包”到一个可执行文件中。它非常方便,但在这种情况下,“虚拟化”功能搞乱了我的程序Environment
变量。我已经设法解决了这个问题。
Environment.CurrentDirectory 为您提供当前工作目录
让我举一个简单的例子:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Startup: " + Environment.CurrentDirectory);
Environment.CurrentDirectory = @"D:\temp";
Console.WriteLine("After:" + Environment.CurrentDirectory);
}
}
现在我创建两个文件夹,名为D:\temp
and D:\temp2
我将可执行文件放入D:\temp
打开命令提示符并设置当前工作目录cd D:\temp2
从该目录我运行..\temp\mytestapp.exe
输出是
Startup: D:\temp2
After: D:\temp
作为一个好奇心:
这是文档环境.当前目录 http://msdn.microsoft.com/en-us/library/system.environment.currentdirectory%28v=vs.71%29.aspx在网络1.1中
获取和设置当前目录的完全限定路径;那
是,该进程开始的目录。
这是 NET 4.0 中的文档
获取或设置当前工作的完全限定路径
目录。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)