c# - 复制图像并覆盖现有图像的问题 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);
}
}
解决方案
您的删除逻辑似乎有问题。
if (!File.Exists(destPath)) // <-- RIGHT HERE
{
File.Delete(destPath);
MessageBox.Show("borrado" + destPath);
}
您实际上是在说,如果文件不存在,请将其删除。
也许它应该是这样的:
if (File.Exists(destPath))
{
File.Delete(destPath);
MessageBox.Show("borrado" + destPath);
}
推荐阅读
- amazon-web-services - 无法使用 Terraform 在自定义 VPC 中创建 Elastic Beanstalk 应用程序
- c# - 按动态参数排序
- python - 朱莉娅中的分布式微积分与python导入代码:UndefVarError:__anon__未定义
- sql - 通过 SQL 中的多维查找填充列?
- c# - 应用程序卡在 File.OpenText()
- r - 错误:“desk”的包或命名空间加载失败:包“desk”是在 R 4.0.0 之前安装的:请重新安装
- r - 填写缺失的日期向前填写 R
- amazon-web-services - S3 对象与文件相同吗?
- amazon-cloudwatch - 确定哪些 SES 调用正在使用版本 2 签名登录
- amazon-web-services - 尝试在 localstack 上创建任何 terraform 资源时超时