首页 > 解决方案 > 复制图像并覆盖现有图像的问题 c# wpf

问题描述

我有一个图像控件,我通过保存在 bdd 中的路径为图像充电,但是如果我想更改图像,首先我用 openfiledialogs 查找新图像向我发送错误,[进程无法访问文件]这个是我的代码

OpenFileDialog openFileDialog = new OpenFileDialog();
        openFileDialog.Multiselect = false;
        openFileDialog.Filter = "Image files (*.;*.jpg)|*.jpg;*.png|All files (*.*)|*.*";
        openFileDialog.FilterIndex = 1;
        openFileDialog.RestoreDirectory = true;
        bool? checarOK = openFileDialog.ShowDialog();
        if (checarOK == true)
        {
            try
            {
                string archivo = openFileDialog.FileName;  //nombre archivo seleccionado
                rtjpg.Text = archivo; //ruta de archivo seleccionado en un textbox
                imgfoto.Source = new BitmapImage(new Uri(openFileDialog.FileName)); //coloca la imagen en un control image
            }
            catch
            {
            }
            try
            { 
                string origPath = rtjpg.Text; //guarda la ruta original de la imagen
                string filename = "mdk_fr_" + nid + "_" + idpac.Text + ".jpg"; //nombre que se le dara a la copia
                string target_path = @"c:\medikfile\imagenes\"; // carpeta destino de la imagen
                string dest_file = Path.Combine(target_path + filename); //ruta completa de la copia
                string destPath = dest_file;
                destruta.Text = destPath;
                if (!File.Exists(destPath))
                {
                    File.Delete(destPath);
                    MessageBox.Show("borrado" + destPath);
                }
                else
                {
                    //                /////
                    int bufferSize = 1024 * 1024;
                    using (FileStream fileStream = new FileStream(destPath, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.ReadWrite))
                    {
                        FileStream fs = new FileStream(origPath, FileMode.CreateNew, FileAccess.ReadWrite);
                        fileStream.SetLength(fs.Length);
                        int bytesRead = -1;
                        byte[] bytes = new byte[bufferSize];

                        while ((bytesRead = fs.Read(bytes, 0, bufferSize)) > 0)
                        {
                            fileStream.Write(bytes, 0, bytesRead);
                        }
                    }
                }
            }
            catch (Exception im)
            {
                MessageBox.Show("error " + im);
            }
        }

标签: c#wpf

解决方案


您的删除逻辑似乎有问题。

if (!File.Exists(destPath)) // <-- RIGHT HERE
{
    File.Delete(destPath);
    MessageBox.Show("borrado" + destPath);
}

您实际上是在说,如果文件不存在,请将其删除。

也许它应该是这样的:

if (File.Exists(destPath))
{
    File.Delete(destPath);
    MessageBox.Show("borrado" + destPath);
}

推荐阅读