使用OpenFileDialog实现图片上传

demo效果图:

注意:图片是存在项目的\bin\Debug\Images下

一个引用:using System.IO;

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 上传图片到指定文件夹
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //初始化openFileDialog
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Title = "请选择要上传的图片";
            ofd.Filter = "图像文件(*.jpg;*.gif;*.png)|*.jpg;*.gif;*.png";
            ofd.Multiselect = false;

            if (ofd.ShowDialog() == DialogResult.OK)
            {
                string oldFilePath = ofd.FileName;
                int position = oldFilePath.LastIndexOf("\\");
                string OldfileName = oldFilePath.Substring(position + 1);
                string[] splitName = oldFilePath.Split('.');
                string ext = splitName[splitName.Length - 1];

                string newName = DateTime.Now.ToString("yyyyMMddhhmmss")+"."+ext;

                //判断根目录下是否含有指定文件夹,若没有则创建一个新的
                string path = AppDomain.CurrentDomain.BaseDirectory+"/Images";
                DirectoryInfo di = new DirectoryInfo(path);
                if (!di.Exists)
                {
                    di.Create();
                }
                string newFilePath = AppDomain.CurrentDomain.BaseDirectory+ "/Images" + newName;

                File.Copy(oldFilePath, newFilePath, true);
                Image img = Image.FromFile(newFilePath);
                pictureBox1.Image = img;
            }
        }
    }
}

 

posted @ 2016-06-26 17:56  草原獒情  阅读(1513)  评论(0编辑  收藏  举报