程序无法在打开拖放文件时从相对路径加载图像
我有一个用 C# 编写的程序,它使用 Image.FromFile 加载图像,并且每次都会成功加载图像。但是,当您将另一个文件拖放到可执行文件上时,例如您向程序提供该文件的命令行参数,并且该文件与可执行文件不在同一文件夹中,则程序会崩溃,因为它显示了该文件的路径文件不存在,即使它存在。
我认为通过将文件放在可执行文件上,它会以某种方式更改加载图像的路径。我该如何解决这个问题?
I have a program I have written in C#, which loads an image with Image.FromFile, and it loads the image successfully every time. However, when you drag and drop another file on the executable, like you are giving the program the command line argument of the file, and the file is not in the same folder as the executable, the program crashes because it says the path to the file does not exist, even though it does.
I think that by dropping a file on the executable, it's changing the path it's loading images from somehow. How can I fix this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的程序将以不同的Environment.CurrentDirectory 启动。始终确保使用绝对路径名加载文件(即不要使用Image.FromFile("blah.jpg"))。
例如,要获取与 EXE 存储在同一目录中的文件的绝对路径,可以使用 Application.StartupPath。或者如果您不使用 Windows 窗体,则为 Assembly.GetEntryAssembly().Location。
Your program would be started with a different Environment.CurrentDirectory. Always make sure you load files with an absolute path name (i.e. don't use Image.FromFile("blah.jpg")).
To get the absolute path to a file that's stored in the same directory as your EXE, you could use Application.StartupPath for example. Or Assembly.GetEntryAssembly().Location if you don't use Windows Forms.
这取决于您如何在应用程序外部启动文件拖动。如果您从 Windows 资源管理器中单击并拖动文件,完整绝对路径名将包含在拖放中。在这种情况下,以下代码显示文件名并将文件内容拖放到文本框中:
因此,请让我们了解有关您的拖动源的更多信息。您很可能必须修改源以拖动绝对路径,或者以某种方式从拖动数据中的相对路径确定完整路径。
此外,您的程序不应因数据错误而崩溃。检查所需的条件,或在必要的代码周围使用 try/catch 块。
It depends on how you are initiating the file drag outside of your application. If you click and drag a file from Windows Explorer, the full absolute path name is included in the drop. In this case the following code shows the filename and performs a drop of the file's contents into a textbox:
So let us know more about your drag source. Most likely you will have to modify your source to drag the absolute path, or somehow determine the full path from the relative path in the drag data.
Also, your program should never crash due to bad data. Either check for the required conditions, or use a try/catch block around the necessary code.