Move a file from one directory to other.

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hello!
I want to move file from one directory to other.
The exception is:
“The process cannot access the file because it is being used by another
process.â€
Maybe it is because I use this file in the project, and do some operations
on it,
And then try to move it to other folder?
Maybe I forget something? ("Free" the file?) or something else ?
Thank U for your help ...

Value of the program:
bckUpFilePath = @"c:\BckUpRet\"
OrgFileName="DocDraft1.txt"

Code:
fi = di.GetFiles();
bckUpFilePath = sBckUpDirectory + "\\";
foreach (FileInfo fTemp in fi)
{
OrgFileName  = fTemp.Name;
// Ensure that the target file does not exist.
if (File.Exists(bckUpFilePath+OrgFileName))     <--- works
File.Delete(bckUpFilePath+OrgFileName);           <--- works   // Move this
file to another file.   fTemp.MoveTo(bckUpFilePath+OrgFileName);  <--- don’t
work
}

Thanks again.
 
It sure looks to me like you're deleting a file, and then trying to move
it...

--
HTH,

Kevin Spencer
Microsoft MVP
Professional Development Numbskull

Nyuck nyuck nyuck
 
Not to me it doesn't - unless "di" is the same as "bckUpFilePath"... rather,
it looks like he's deleting the /old/ backup (if it exists), then moving the
current fTemp to the same location.

My guess would be a FileStream (or similar) that hasn't been Close()d and
Dispose()d.

Some other thoughts... "copy" is more common with backups, no? And you might
want to think about what happens to the backup when the move/copy fails...
i.e. you just canned it "whoops, no backup".

Marc
 
Marc Gravell said:
Not to me it doesn't - unless "di" is the same as "bckUpFilePath"... rather,
it looks like he's deleting the /old/ backup (if it exists), then moving the
current fTemp to the same location.

My guess would be a FileStream (or similar) that hasn't been Close()d and
Dispose()d.

Some other thoughts... "copy" is more common with backups, no? And you might
want to think about what happens to the backup when the move/copy fails...
i.e. you just canned it "whoops, no backup".

Marc
Marc Gravell,
Thank you I just closed the file and it works.
You really helped me!
 
For reference - to avoid this type of thing in future, "using" is your
friend...

using(FileStream stream = File.Open(blah)) {
// do something 'orribly complex
stream.Close();
}

This way, even if the method barfs with an exception the stream will get
Dispose()d and the file should be released. A little trickier if you want to
hold the stream for an indefinite time, but do-able.

Marc
 
Yes, you're right Marc. I've been too busy lately!

--
HTH,

Kevin Spencer
Microsoft MVP
Professional Development Numbskull

Nyuck nyuck nyuck
 
Back
Top