I am writing an application that allows the user to import a picture from the computer and view it in my application. The user also has an import button under the picture and he/she can select the picture's destination in the computer.
My problem is that I get following exception:
System.IO.IOException: 'The process cannot access the file 'D:\Workspaces_Foo\Foo\Theme\MyPic.png' because it is being used by another process.'
when I debug it I find the line where it's breaking. It is in:
string image = Constants.ImageName;
if (image != "NONE")
{
using (var stream = File.OpenRead(SourceDir + ImageName))
{
Directory.CreateDirectory(Path.GetDirectoryName(DestinationDir + "\\" + image));
File.Copy(SourceDir + "\\" + image, DestinationDir + "\\" + image, true); //breaks here...
}
}
I assumed that by using a filestream it would've allowed me to continue with my picture transfer. Can anyone tell me why I am getting this error?
答案 0 :(得分:3)
您正在打开该文件的流。这将打开文件并将其标记为正在使用中。
然后你使用File.Copy来复制它,但是操作系统说文件正在使用中(它不够聪明,注意到你的进程正在使用它!)
忘掉流,试试吧。
var processes = Process.GetProcesses()
.Where(p=> p.MainWindowHandle != 0)
.ToArray();