File.Move

E

edi

Hi,

I'm trying to move a file using File.Move(path1,path2). But the file
does not close immediately I call the method (I use Word library to
manage word file).
I can do something like this:

tryagain:
try
{
File.Move(e.FullPath,txtProcessedFile.Text+e.Name);
}
catch
{
goto tryagain;
}

Is there any alternative of this (I don't want to use "goto")?

Thanks.
 
D

DalePres

There are two problems with your code. The first one, you have identified:
Using goto is not generally an acceptable option. The second problem is
that you do not have any means of breaking your loop. If there is a problem
saving the file, the loop will continue forever.

To fix your code, I suggest that you put your save functionality in another
method and use a while loop to call the method something like this:

bool done = false;
while (!done)
{
done = SaveFile(e.FullPath, txtProcessedFile.Text + e.Name);
}

private bool SaveFile (string source, string destination)
{
try
{
File.Move(e.FullPath,txtProcessedFile.Text+e.Name);

// Insert code to verify that the new file actually exists here and
if it does:
return true;
}
catch
{
// Insert code here that can break the while loop - in other words,
return true if the user
// doesn't want to try saving again. Otherwise:
return false;
}
}

HTH

Dale Preston
MCAD, MCDBA, MCSE
 
M

Morten Wennevik

Hi edi,

As DalePres said, simply looping through the same exception will get you
nowhere.

Chances are the new filename is occupied, for file moving like this I
prefer to use File.Exists(filename) in a manner similar to this:

char c = 'a';

string filename = txtProcessedFile.Text + e.Name;

while(File.Exists(filename)
{
filename = txtProcessedFile.Text + e.Name + c;
c++;
}

File.Move(e.FullPath, txtProcessedFile.Text + e.Name);

This way the code will keep trying to move the file, but for every loop
the new filename is changed ever so slightly until an unoccupied filename
is found. Use a character or a number or any other means to create new
file names.

PS! I don't think this affects you, but when dealing with files, you
can't be 100% sure the file will be moved/deleted instantly as Windows
itself has a miniscule delay. Changing a filename to a file that was
just deleted might cause an exception.
 

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

Similar Threads


Top