【发布时间】:2014-08-24 14:15:50
【问题描述】:
我的代码是这样的:
using (var openFileDialogForImgUser = new OpenFileDialog())
{
string location = null;
string fileName = null;
string sourceFile = null;
string destFile = null;
string targetPath = @"..\..\Images";
openFileDialogForImgUser.Filter = "Image Files (*.jpg, *.png, *.gif, *.bmp)|*.jpg; *.png; *.gif; *.bmp|All Files (*.*)|*.*"; // filtering only picture file types
openFileDialogForImgUser.InitialDirectory = @"D:\My Pictures";
var openFileResult = openFileDialogForImgUser.ShowDialog(); // show the file open dialog box
if (openFileResult == DialogResult.OK)
{
using (var formSaveImg = new FormSave())
{
var saveResult = formSaveImg.ShowDialog();
if (saveResult == DialogResult.Yes)
{
imgUser.Image = new Bitmap(openFileDialogForImgUser.FileName); //showing the image opened in the picturebox
fileName = openFileDialogForImgUser.FileName;
location = Path.GetDirectoryName(fileName);
sourceFile = System.IO.Path.Combine(location, fileName);
destFile = System.IO.Path.Combine(targetPath, fileName);
if (!System.IO.Directory.Exists(targetPath))
{
System.IO.Directory.CreateDirectory(targetPath);
}
System.IO.File.Copy(sourceFile, destFile, true); /* error occurs at this line */
}
else
openFileDialogForImgUser.Dispose();
}
}
}
我想要做的是提示用户在 OpenFileDialog 中选择一个图像,然后将该图片复制到不同的目录(特别是 targetPath)。除了那一行:System.IO.File.Copy(sourceFile, destFile, true);。
它表示该文件被另一个进程独占使用。我选择的任何图像都会发生这种情况。
我正在尝试查看其他人对此问题的解决方案 --- 我必须终止(或等待)正在使用我的文件的进程。如果是这样,我该怎么做?或者,如果这不是这个问题的答案,我该怎么办?请注意,这是我的 C# 解决方案中唯一处理图像文件的代码。
【问题讨论】:
-
您知道哪个进程正在使用您的文件吗?你能控制它吗?
-
老实说 --- 不,我没有。我相信,该文件仅在此方法中使用,没有在其他地方使用。
-
使用Process Explorer 等工具查看谁拥有您文件的打开句柄
-
我使用的IDE是VS 2013,
.vhost.exe正在使用该文件。