0

我有一个带有“图像”文件夹的 Windows 应用程序。我需要在运行时检查图像是否存在,它会存在。下面的代码是我所拥有的,但它总是返回 false。

 if ( File.Exists("images/" + item.tool_image) )
        {
            Image img;
            img = Image.FromFile("images/" + item.tool_image);
            titem.Image = img;
        }

什么问题或正确的方法来做到这一点。

4

6 回答 6

3

如果您要查找的文件在应用程序的工作目录中不存在,请File.Exists使用标准路径调用:

if (File.Exists(@"C:\images\" + item.tool_image))
{ ... }

当然,请验证文件是否确实存在于该位置。

如果您使用该Path课程提供的工具,您会发现生活更轻松:

if (File.Exists(Path.Combine(@"C:\images", item.tool_image)))
{ ... }
于 2011-11-13T05:32:15.527 回答
1

路径错误尝试将其更改为

 string basePath = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
            string imageFileName = System.IO.Path.Combine(basePath, "Images",item.tool_image);
     if ( File.Exists(imageFileName) )
            {
                Image img;
                img = Image.FromFile(imageFileName);
                titem.Image = img;
            }
于 2011-11-13T05:52:02.357 回答
1

如何在 Windows 应用程序中正确使用 File.Exists?

你没有!

在尝试打开文件之前检查文件是否存在几乎是不合适的。这里还有其他事情在起作用:权限、锁定、共享、时间。

相反,执行此操作的正确方法是尝试打开文件,无论它是否存在,然后在您尝试打开文件失败时捕获异常。无论如何,您必须能够处理此异常,即使在执行 File.Exists() 检查之后也是如此。这使您的初始 File.Exists() 检查不仅对您的代码是多余的,而且是浪费的,因为它会导致额外的文件系统之旅......而且在编程中您可以做的事情并不多,这比访问文件要慢系统。

于 2011-11-13T05:52:49.417 回答
0

它是从代码当前运行的位置看的,“/”也是错误的方向。此外,您正在多个地方定义路径,这可能会导致以后出现问题。

var path = string.Format(@"c:\somewhere\images\{0}", item.tool_image);
if (File.Exists(path))
{
   Image img;
   img = Image.FromFile(path);
   titem.Image = img;
}

设置变量由您决定path,但很可能,在您的代码示例中,您期望的位置没有被检查。

于 2011-11-13T05:32:58.870 回答
0

您调用它的方式是在图像文件夹中查找字符串 item.tool_image 中的任何文件。请注意,此图像文件夹位于包含您的可执行文件的任何目录中。

例如,我刚刚调用 File.Exists("images/image.jpg") 并且它起作用了。

于 2011-11-13T05:33:00.693 回答
0

正如每个人都提到的,使用完全限定的路径。我还大量使用 Path.Combine,因此在组合目录时不必担心会丢失一两个斜线。当前的执行目录也很有用...

File.Exists(Path.Combine(Environment.CurrentDirectory, "Images", item.tool_image));
于 2011-11-13T05:35:29.803 回答