【问题标题】:How to set relative path to Images directory inside C# project?如何在 C# 项目中设置图像目录的相对路径?
【发布时间】:2013-03-29 03:20:54
【问题描述】:

我正在处理 C# 项目,我需要使用相对路径从图像目录中获取图像。我试过了

var path = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) + @"\Images\logo.png";
var logoImage = new LinkedResource(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)+@"\Images\logo.png")

但是这些都没有运气...... 当程序运行时,我已将图像复制到输出目录,但它没有拾取这些图像。

【问题讨论】:

  • 如何使用相对路径获取Images目录?

标签: c# relative-path


【解决方案1】:

如果您在 C# 中使用 LinkedResource(),则很可能不会获取您的相对 URI 或文件位置。

你可以使用一些额外的代码

var outPutDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
var logoimage = Path.Combine(outPutDirectory, "Images\\logo.png");
string relLogo = new Uri(logoimage).LocalPath;
var logoImage = new LinkedResource(relLogo)

现在它将获取您的相对路径,将其转换为内存中的绝对路径,它将帮助您获取图像。

【讨论】:

    【解决方案2】:

    我会确保图像目录位于输出文件夹中。 我通常使用Assembly.GetExecutingAssembly().Location 来获取我的 dll 的位置。

    但是,对于图像,我通常使用项目属性页面中的资源页面/集合。 Here 是关于它的更多信息。将图像放入项目的资源中会自动为您提供访问它的简单方法。

    有关 GetExecutingAssembly 的更多信息:MSDN Page

    【讨论】:

      【解决方案3】:

      首先,将这些图像文件添加到您的项目中(创建一个图像文件夹是个好主意)

      其次,在你的解决方案管理器中选择图片,查看属性窗口。

      然后,将“复制到输出文件夹”更改为“始终”或“更新时复制”。

      PS。我的 IDE 是繁体。中文,所以我无法确保您的语言中的关键字正确。

      【讨论】:

      • 对不起,我可能误解了你的问题。但是,您检查过pathlogoImage 的值吗?我想它可能不是“\”或很多。
      【解决方案4】:

      如果您想使用您的应用程序在您的文件夹中显示图像,请使用数组并将您文件夹中的所有图片放入数组中。然后你可以前进和后退。

      string[] _PicList = null;
      
      int current = 0;
      
      _PicList = System.IO.Directory.GetFiles("C:\\Documents and Settings\\Hasanka\\
                                                     Desktop\\deaktop21052012\\UPEKA","*.jpg"); 
      // "*.jpg" will select all 
      
      //pictures in your folder
      
      
      String str= _PicList[current];
      
      DisplayPicture(str);
      
      private void DisplayPicture(string str)
      
      {
          //throw new NotImplementedException();
          BitmapImage bi = new BitmapImage(new Uri(str));
          imagePicutre.Source = bi; // im using Image in WPF 
          //if u r using windows form application it must be a PictureBox i think.
      
          label1.Content = str;
      
      }
      

      【讨论】:

      • 我知道如何使用绝对路径,但我的上下文是使用相对路径
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-05
      • 2010-11-27
      • 1970-01-01
      • 1970-01-01
      • 2017-09-07
      • 1970-01-01
      相关资源
      最近更新 更多