用流的方法解决“文件正由另一进程使用,因此该进程无法访问该文件” 的问题 FileStream

            第一种方法:会遇到“文件正由另一进程使用,因此该进程无法访问该文件” 的错误。

            string fPath = @"PsonPhoto/" + chInfo.Idcard.Trim() + ".bmp";
            //this.picPhoto.Image = Image.FromFile(@"PsonPhoto/" + chInfo.Idcard.Trim() + ".bmp", false);
            //Image img1 = Image.FromFile(@"PsonPhoto/" + chInfo.Idcard.Trim() + ".bmp", false);
            //Image img2 = new Bitmap(img1);       
            //img1.Dispose();
            //GC.Collect();
            //this.picPhoto.Image = img2;

 

            //try
            //{
            //    //删除Run/Psonphoto下的照片,命名为“IDCARD111.bmp”
            //    //System.IO.FileInfo file = new System.IO.FileInfo(@"PsonPhoto/" + _picFhoto + ".bmp");
            //    //if (file.Exists)
            //    //{
            //    //    file.Delete();
            //    //}
            //    if (isHotKey == "1")
            //    {
            //        if (File.Exists(@"PsonPhoto/" + _picFhoto + ".bmp"))
            //        {
            //            File.Delete(@"PsonPhoto/" + _picFhoto + ".bmp");
            //        }
            //    }
            //}
            //catch (Exception ex)
            //{
            //    MessageBox.Show(ex.Message, "警告", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            //}

 

 

 

 

 

            第二种方法:顺利通过!!!

            FileStream fs = new FileStream(fPath, FileMode.Open);
            BinaryReader br = new BinaryReader(fs);
            byte[] bytes = br.ReadBytes((int)fs.Length);
            br.Close();
            fs.Close();
            MemoryStream ms = new MemoryStream(bytes);
            this.picPhoto.Image = System.Drawing.Image.FromStream(ms);
            File.Delete(fPath);

你可能感兴趣的:(用流的方法解决“文件正由另一进程使用,因此该进程无法访问该文件” 的问题 FileStream)