Click here to Skip to main content
16,020,840 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am getting exception File is used by another Process while moving files in C#. I am moving files in a Windows service from a source folder to another folder as configured.

What I have tried:

My code is as below:
C#
Common.MoveFile(FilewithPath, LocalFilePath + FileName)
 public static bool MoveFile(string sourcefile, string destinationfile)
        {
            try
            {

                Common.WriteLogService
                ("File Movement Process Started", "MoveFile()", false);
                if (File.Exists(sourcefile))
                {
                    if (File.Exists(destinationfile)) //delete destination 
                    // file if it already exists to avoid exception 
                    //of file already exists
                    {
                        File.Delete(destinationfile);
                    }
                    File.Move(sourcefile, destinationfile);
                    Common.WriteLogService("File:" + sourcefile + 
                    " Moved to" + destinationfile, "MoveFile()", false);
                }

                Common.WriteLogService("File Movement Process Completed", 
                                       "MoveFile()", false);
            }
            catch (Exception ex)
            {
                Common.WriteLogService("File Movement Process failed 
                     with Exception: " + ex.Message + Environment.NewLine
                     + " with Inner Exception: " + ex.InnerException + 
                     Environment.NewLine + " at Stack Trace: " + 
                     ex.StackTrace, "MoveFile()", true);
                return false;               
            }
            return true;
        }
Posted
Updated 19-Sep-23 10:52am
v2
Comments
Dave Kreskowiak 18-Sep-23 7:50am    
Are you using a FileSystemWatcher to move files written by a different app?

1 solution

You can't "avoid" it: if a file is opened for writing and not closed then the OS applies a lock on the file, and it remains locked until the original code either closes the file or exits and it's process resources are released back to the OS.

At a guess, somewhere in your code you are accessing the file, but not closing it: you need to find out where and deal with it, but we can't help you do that - we have no access to your code!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900