找不到文件异常发生

时间:2017-07-21 07:33:25

标签: c# winforms filenotfoundexception imagelist

我的项目中有一个图像列表。所以我需要在窗口代码后面的图像列表中添加图像。

我的项目中有一个名为Myimages的文件夹。在那个文件夹中我有一些图像。

所以我尝试这样:

imageList1.Images.Add(Image.FromFile(@"Myimages\dog.ico"));

imageList1.Images.Add(Image.FromFile(@"~\Myimages\cat.ico"));

 imageList1.Images.Add(Image.FromFile(@"/Myimages/horse.ico"));

但我无法做到这一点。它使 FileNotFoundException

错误:

  

“System.IO.FileNotFoundException”类型的未处理异常   发生在System.Drawing.dll

中      

其他信息:/Myimages/horse.ico

如何解决此错误。帮助赞赏!!

当我使用像C:\MyProject\Myimages\horse.ico这样的完整路径时。它为我工作。 但是,当我给出像“Myimages\horse.ico”这样的路径时,它会给出异常。

3 个答案:

答案 0 :(得分:2)

  

当我使用像C:\MyProject\Myimages\horse.ico这样的完整路径时。它为我工作。但是,当我给出像Myimages\horse.ico这样的路径时,它会给出异常。

因为相对路径是从* .EXE文件的位置搜索的。它位于C:\MyProject\bin\DebugC:\MyProject\bin\Release文件夹中。在潜入Myimages之前,您需要移动2个文件夹。试试这个相对路径:

  

..\..\Myimages\horse.ico

编辑:

如果您的解决方案文件夹与您的项目文件夹具有相同的名称,那么您会比我想象的更深一层。请在这种情况下再试一次

  

..\..\..\Myimages\horse.ico

免责声明:只要您将* .EXE相对于MyImages文件夹移动,此方法就会给您带来麻烦。例如,在同一文件夹中,则此路径将是错误的。

编辑2:请您使用以下格式:

imageList1.Images.Add(Image.FromFile(@"..\..\..\Myimages\horse.ico"));

答案 1 :(得分:1)

使用相对路径时,例如

 @"/MyImages/horse.ico"

实际的完整路径是

 Path.Combine(Environment.CurrentDirectory, @"/MyImages/horse.ico");

请检查Environment.CurrentDirectory值,您可以看到系统尝试查找/Myimages/horse.ico文件的位置。如果需要,您可以修改Environment.CurrentDirectory

 // When relative path provided look at C:\MyFiles
 Environment.CurrentDirectory = @"C:\MyProject";

编辑:如果您不想将绝对路径(例如@"C:\MyProject")设置为默认路径,则可以尝试从入口点程序集(例如exe文件)

using System.Reflection;

...

// One level down the directory where exe file lies
string path = 
  Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "..");

答案 2 :(得分:0)

如果是Web应用程序。然后使用Server.MapPath

string fileRelativePath = "~/Content/Gallery/" + Path.GetFileName(path);
image.Save(HttpContext.Current.Server.MapPath(fileRelativePath));