winform openFileDialog 多个文件上传

 


 



 

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------

        private void button1_Click(object sender, EventArgs e)
        {
            openFileDialog1.ShowHelp = false;//设置是否显示"帮助"按钮
            //openFileDialog1.InitialDirectory = "D:\\";//设置初始目录为D盘
            openFileDialog1.Title = "选择图片";//设置对话框的标题
            openFileDialog1.FileName = "";//设置初始选择的文件名为空
            openFileDialog1.Multiselect = true;//设置对话框为单选
            openFileDialog1.Filter = "All Files (*.*)|*.*|Image Files(*.jpg)|*.jpg|PNG图片(*.png)|*.png|Excel Files (*.xls)|*.xls";//"PNG图片|*.png|JPG图片|*.jpg|GIF图片|*.gif"; //筛选文件
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                textBox1.Text = System.IO.Path.GetFullPath(openFileDialog1.FileName); //获取文件路径
                pictureBox1.Image = Image.FromFile(openFileDialog1.FileName); //显示

                foreach (string filename in openFileDialog1.FileNames)
                {
               
                    //var fileNm = Path.GetFileName(textBox1.Text);
                    var name = Path.GetFileName(filename); //获取文件名称
                    string dir = AppDomain.CurrentDomain.BaseDirectory; //当前运行目录
                    var url = Path.Combine(dir, "images", name);  //拼接上传路径

                    //读
                    using (FileStream fir = new FileStream(filename, FileMode.Open, FileAccess.Read))
                    {
                        //写
                        using (FileStream des = new FileStream(url, FileMode.OpenOrCreate, FileAccess.Write))
                        {
                            //将得到的文件流复制到写入流中
                            fir.CopyTo(des);
                            //将写入流中的数据写入到文件中
                            des.Flush();

                        }
                    }
                }

                //方法2
                //byte[] buffer = new byte[fir.Length]; int size = 0; int ren = 0;
                //while (ren < fir.Length)
                //{
                //    Application.DoEvents();
                //    size = fir.Read(buffer,0, buffer.Length); 
                //    des.Write(buffer,0 , size);
                //    ren += size;
                //}

            }
        }

  

 

posted @ 2023-07-10 12:03  cclon  阅读(422)  评论(0编辑  收藏  举报