[英]C# Directory.GetCurrentDirectory and drives other than C:
For some reason when my program is installed on a drive other than C:\\ the code below (c# .net 2.0) is unable to find and run the program2.exe. 由于某些原因,当我的程序安装在C:\\以外的驱动器上时,下面的代码(c#.net 2.0)无法找到并运行program2.exe。 Am I doing something wrong here? 我在这里做错什么了吗?
try
{
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.FileName = Directory.GetCurrentDirectory() +
"\\Folder\\program2.exe";
proc.Start();
}
catch
{
MessageBox.Show("Unable to locate program");
}
Could it be because your program is in the root folder of another drive, eg R:\\
, rather than a subdirectory, eg R:\\Program
? 可能是因为您的程序位于另一个驱动器的根文件夹中,例如R:\\
,而不是子目录例如R:\\Program
?
For reasons such as this, it is considered bad practice in C# to concatenate paths using the literal backslash character. 由于诸如此类的原因,在C#中使用文字反斜杠字符连接路径被认为是不好的做法。 Instead, you should use Path.Combine
: 相反,您应该使用Path.Combine
:
proc.StartInfo.FileName = Path.Combine(
Directory.GetCurrentDirectory(),
"Folder",
"program2.exe"
);
Furthermore, it may be that Directory.GetCurrentDirectory()
does not point to the directory you think it does. 此外,可能Directory.GetCurrentDirectory()
没有指向您认为的目录。 In general, this could return any directory on your system, and is unrelated to where your program resides or was launched from. 通常,这可以返回系统上的任何目录,并且与程序所在的位置或启动程序的位置无关。 Therefore, I recommend to use one of these instead: 因此,我建议改用以下方法之一:
Application.ExecutablePath
如果您使用的是WinForms,则Application.ExecutablePath
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)
否则, Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.