原理是: 在\bin\Debug 目录下建一个目录保存上传的图片
打开对话框获取图片绝对路径 用System.IO.File的Copy方法 把源路径的文件复制到\bin\Debug下新建的目录, 数据库保存文件名
使用时用数据库保存文件名和相对路径调用
private void button1_Click(object sender, EventArgs e) { //debug文件夹下建文件夹Photo //数据库存入 //创建文件对话框对象 OpenFileDialog ofd = new OpenFileDialog(); ofd.Title = "请选择上传的图片"; ofd.Filter = "图片格式|*.jpg"; ofd.Multiselect = false; if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK) { //获得文件的完整路径 string filePath = ofd.FileName; txtImageFile.Text = filePath; //int position = filePath.LastIndexOf("\\"); //string photoName = filePath.Substring(position + 1); //获取最后一个点的位置(图片后缀名) int position = filePath.LastIndexOf("."); string geshi = filePath.Substring(position); //重命名该文件 string photoName = txtname.Text + geshi; //上传至指定程序所在的debug文件夹下,并在pictureBox中显示 //如果存在,则删除 if (System.IO.File.Exists(Application.StartupPath + "\\Photo\\" + photoName)) { System.IO.File.Delete(Application.StartupPath + "\\Photo\\" + photoName); } //System.IO.File.Delete(Application.StartupPath + "\\Photo\\" + photoName) System.IO.File.Copy(ofd.FileName, Application.StartupPath + "\\Photo\\" + photoName); pictureBox1.ImageLocation = Application.StartupPath + "\\Photo\\" + photoName; //数据库存入 该文件名 photoName //如果需要调用该图片,则只需要通过数据库中的图片名,和文件夹Photo下的文件名调用即可; } }