mmangual83
mmangual83

Reputation: 151

Having issues setting up a simple filestream

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?

Upvotes: 0

Views: 43

Answers (1)

Stephen Turner
Stephen Turner

Reputation: 7314

You are opening a stream for the file. This opens the file and marks it as in use.

Then you use File.Copy to copy it, but the Operating system says the file is in use (it isn't clever enough to notice that it is in use by your own process!)

Forget the stream, try this instead.

string image = Constants.ImageName;
if (image != "NONE")
{
    Directory.CreateDirectory(Path.GetDirectoryName(DestinationDir + "\\" + image));

    File.Copy(SourceDir + "\\" + image, DestinationDir + "\\" + image, true);
}

Upvotes: 3

Related Questions