问题
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