【问题标题】:Load image from relative path in C# Windows Forms从 C# Windows 窗体中的相对路径加载图像
【发布时间】:2020-11-27 14:33:53
【问题描述】:

我的应用程序中有一个图片框,我不确定如何设置相对路径。 我的目录结构是

components
    icons
     -- warning.png
    myCustomBox.cs

所以我正在尝试从 myCustomBox.cs 设置图像

imageBox.Image = Image.FromFile(@"C:\Users\mike\source\repos\Management\components\icons\warning.png");

我想要这样的相对路径

imageBox.Image = Image.FromFile("/icons/warning.png");

谁能帮帮我?

我确实找到了问题的答案,但没有运气会引发相同的“找不到文件”错误 Loading image from relative path in Windows Forms

下面是我的代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Management
{
    public partial class myCustomBox: Form
    {
        public myCustomBox()
        {
            InitializeComponent();
        }

        private void showIcon_Click(object sender, EventArgs e)
        {
            imageBox.Image = Image.FromFile("/icons/warning.png");
        }
    }
}

【问题讨论】:

  • tried it out but no luck 发布那个代码。如果它对您不起作用,那么一定是某个地方出现了一个简单的错误,但是没有看到实际代码,没有人能猜出是什么或在哪里。
  • 我已经在代码中添加了。
  • 1) 发布的代码没有像linked answer 那样显示任何Path.Combine 的尝试。 2)以"/"开头的路径(或者,Windows中的"\")不是相对路径,而是以当前工作目录驱动为根的绝对路径。

标签: c# windows image relative-path


【解决方案1】:

相对路径与应用程序运行的位置相关,通常是 .exe 文件所在的位置。

在 Visual Studio 中,选择项目中的图像并将“复制到输出目录”属性更改为“如果较新则复制”。然后,当您构建项目时,它会为您将图像复制到您的 bin 文件夹中。

【讨论】:

  • 我目前正在调试模式下运行项目。
  • 这应该没什么区别。
猜你喜欢
  • 2011-09-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-06
  • 1970-01-01
  • 2012-03-16
  • 1970-01-01
相关资源
最近更新 更多