File.Copy error

J

juli jul

Hello,
I am trying to overwrite a file in this way:
File.Copy(this.file_name,this.file_name,true);

The problem is that I get this error:
An unhandled exception of type 'System.IO.IOException' occurred in
mscorlib.dll

Additional information: The process cannot access the file "C:\Documents
and Settings\My Documents\abc.xml" because it is being used by another
process.

I did the :
this.xml_reader.Close();
before I called the File.Copy but I still get this error,why?

Thank you!
 
D

Dale Preston

What are you trying to accomplish? Your method call would, if it worked -
which it won't - just read this.file_name and re-write it to itself. If
you're going to overwrite the file, the assumption is that you want to
modify it in some manner first.

Dale Preston
MCAD, MCDBA, MCSE
 
S

Stephan Steiner

As Dale pointed out, your call doesn't make sense and cannot work.

File.Copy will open the file provided as the first parameter in read-only
mode, open the file provided as the 2nd parameter in write mode. You get the
exception because if you open a file, you cannot open the same file in write
mode again.. write mode requires exclusive access.

So, if for whatever reason you need to overwrite the file with itself.. open
it, read its content to memory, close it again, then open it again in write
mode using the proper flags to indicate that if the file exists it should be
overwritten, then write to the file from the buffer.

Or somply do a File.Copy(file1, file1-temp); File.Delete(file1);
File.Move(file1-temp, file1).

Regards
Stephan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top