hardcoded to relative paths

六眼飞鱼酱① 提交于 2019-12-11 14:35:23

问题


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.

Here's what I have already:

    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");
    }
}

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

Thanks in advance!


回答1:


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);

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.



来源:https://stackoverflow.com/questions/23626597/hardcoded-to-relative-paths

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!