使用OpenFileDialog()打开文件

OpenFileDialog ofd = new OpenFileDialog();
ofd.InitialDirectory = @"C:\Users\Administrator\Desktop";//设置默认打开地址,如不设置就是打开程序所在的文件夹(绝对路径)
//ofd.InitialDirectory = Directory.GetCurrentDirectory().ToString()+"\\A";//获取程序所在路径的子目录
ofd.Filter = "图片(*.png)|*.png|所有文件(*.*)|*.*";//设置文件名筛选器
ofd.Title = "请选择一张图片";//设置标题
DialogResult result = ofd.ShowDialog();
if (result == DialogResult.OK)
{
//pb_Pic.Image = Image.FromFile(ofd.FileName);直接引用图片时文件将一直被占用
if (File.Exists(ofd.FileName))//判断当前文件夹下图片是否存在
{
using (FileStream fs = new FileStream(ofd.FileName, FileMode.Open))
{
int len = (int)fs.Length;
byte[] buf = new byte[len];
fs.Read(buf, 0, len);
MemoryStream ms = new MemoryStream();
ms.Write(buf, 0, len);
pb_Pic.Image = Image.FromStream(ms);
pb_Pic.SizeMode = PictureBoxSizeMode.StretchImage;//伸展图片使其适应图片框
}
}
}

猜你喜欢

转载自www.cnblogs.com/GY66520/p/12129505.html