winfrom项目之上传图片

作用原理:把图片文件上传至项目里的某个文件夹下,文件名添加至数据库,展示图片的时候,该文件夹的路径+文件名

在窗体上添加上传图片按钮:

// 需要添加的引用
using System.IO;  // FileInfo
using System.Windows.Forms;  // OpenFileDialog


// 用到的组件: Button、PictureBox、openFileDialog(打开文件管理器)


        public static string img;//声明一个全局变量存储上传之后的文件名


//获取项目根目录
        private static string GetApplicationPath()
        {
            string path = Application.StartupPath;
            string folderName = String.Empty;
            while (folderName.ToLower() != "bin")
            {
                path = path.Substring(0, path.LastIndexOf("\\"));
                folderName = path.Substring(path.LastIndexOf("\\") + 1);
            }
            return path.Substring(0, path.LastIndexOf("\\") + 1);
        }
        //上传按钮事件
        private void btnUpload_Click(object sender, EventArgs e)
        {
            //文件根目录
            string path = GetApplicationPath();
            DialogResult dr = openFileDialog1.ShowDialog();
            if (dr == DialogResult.OK)
            {
                string file = openFileDialog1.FileName;
                string filename = file.Substring(file.LastIndexOf("\\") + 1); //格式化处理,提取文件名
                //MessageBox.Show(name);
                pictureBox1.Image = Image.FromFile(file);
                bool ret = File.Exists(@path + "\\Image\\" + filename);//判断文件是否存在,返回一个bool值
                //MessageBox.Show(ret.ToString());
                if (ret)
                {
                    MessageBox.Show("该图片文件已存在,建议更换");
                }
                else
                {
                    File.Copy(openFileDialog1.FileName, path + "\\Image\\" + filename);
                }
                string imgpath = GetApplicationPath() + "//Image//";
                pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage; //使图像拉伸或收缩,以适合PictureBox
                pictureBox1.Image = Image.FromFile(imgpath + filename);
                img = filename;
            }
       }

winform 获取程序目录及项目的根目录

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值