从另一个应用程序启动可执行文件时找不到文件
在我的应用程序中,用户登录后,我设置了一些图片框/按钮/等图像,并对它们进行一些缩放等等。例如,我使用相对路径:
@".\Images\SomeImage.png"
直接启动应用程序时它工作正常,但如果您尝试通过另一个应用程序运行它:
Process process = new Process();
process.StartInfo.FileName = networkPath;
process.Start();
它会死掉并出现文件未找到错误,因为它无法找到图像。如果我尝试通过命令提示符启动它,它也会执行此操作。可执行文件存储在网络驱动器上。为什么相对路径在这种情况下不起作用?我可以继续对完整路径进行硬编码,但这让我感觉很脏......有什么想法吗?
In my application, after the user logs in I set a few picturebox/button/etc images and do some scaling on them and whatnot. I use relative paths for example:
@".\Images\SomeImage.png"
It works fine when the application is launched directly, but if you try to run it via another application:
Process process = new Process();
process.StartInfo.FileName = networkPath;
process.Start();
It dies and comes up with a file not found error, because it cannot locate the images. It also does this if I try to launch it via the command prompt. The executable is stored on a network drive. Why won't the relative path work in this situation? I can just go ahead and hard code the full path but that makes me feel dirty... Any thoughts?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是因为工作目录不同 - 默认情况下,启动新进程时,新进程的工作目录设置为现有进程的工作目录(这可能是现有应用程序所在的目录)。
通常,您的应用程序将以工作目录作为包含可执行文件的目录运行 - 例如,这是创建新快捷方式时的默认设置(您可以在“开始于”字段下的快捷方式属性中看到这一点。
当您应用程序是从命令提示符或其他应用程序运行的,但是工作目录已更改,并且相对路径已解析为完全不同的目录。
您可以更改调用应用程序以设置
WorkingDirectory
属性新进程达到它期望的值,但是修复此问题的正确方法是修改您的应用程序,以便它使用基于可执行文件路径的绝对路径。Assembly.GetExecutingAssembly().Location
可用于获取正在运行的可执行文件的路径,因此以下代码应该可以解决问题:This is because the working directory is different - by default when starting a new process the working directory for the new process is set to the working directory of the existing process (which will in turn probably be the directory that existing application is contained within).
Normally your application will be run with the working directory as the directory that the executable is contained in - this is the default when creating a new shortcut for example (you can see this in the shortcut properties under the "Start in" field.
When your application is run from the command prompt or from another application however the working directory is changed and the relative paths are resolved to a completely different directory.
You can either change the calling application to se the
WorkingDirectory
property of the new process to the value it expects, however the proper way of fixing this it to modify your application so that it uses absolute paths based on the path to the executable.Assembly.GetExecutingAssembly().Location
can be used to get the path to the executable being run and so the following code should do the trick:您需要设置
Process.WorkingDirectory
属性到正确的路径。
您发布的路径:
不是网络路径(它不是 UNC 或使用映射驱动器)。
You need to set the
Process.WorkingDirectory
property to the correct path.The path you posted:
Is not a network path (it is not UNC or using a mapped drive).