硬编码为相对路径 [英] hardcoded to relative paths

查看:247
本文介绍了硬编码为相对路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在一个项目中,单击一个按钮,我指定的文件夹的随机图像将出现在特定的图片框中.

I'm working on a project that on the click of a button a random image for a folder I specified will appear in a specific picturebox.

这是我已经拥有的:

    namespace WindowsFormsApplication12
    {
public partial class Form1 : Form
{
    Random r = new Random();

    public Form1()
    {
        InitializeComponent();

    }

    private void button1_Click(object sender, EventArgs e)
    {

        pictureBox1.Image = Image.FromFile(r.Next(3).ToString() + ".jpg");
    }
}

现在我如何为此添加相对路径?我的硬编码路径是c:/users/ben/documents/visualstudio/projects/projectnet/resources/pictures.

Now how can i add a relative path to this? My hardcoded path is c:/users/ben/documents/visualstudio/projects/projectnet/resources/pictures.

提前谢谢!

推荐答案

您可以在button1_Click处理程序中尝试使用此方法:

You could try this in your button1_Click handler:

string imageFileName = r.Next(3).ToString() + ".jpg";
string basePath = @"c:\users\ben\documents\visualstudio\projects\projectnet\resources\pictures";

pictureBox1.Image = Image.FromFile(Path.Combine(basePath, imageFileName);

如对问题的评论中所述,如果打算在非您自己的计算机上运行应用程序,则最好从外部源(即app.config)读取基本目录.

As mentioned in the comments to your question it is a good idea to read your base directory from an external source, i.e. app.config, if you intend to run your application on a computer other than your own.

这篇关于硬编码为相对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆