File.Move no longer working

kriscs1

Member
Joined
Jan 30, 2020
Messages
6
Programming Experience
Beginner
Hi,
I have a program that checks a folder for Excel files, imports their contents via SQL to a database table, then moves the Excel file to a 'Completed' folder.
This worked flawlessly last year. Unfortunatley, I am now getting the following error:

System.IO.IOException: The process cannot access the file because it is being used by another process.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.__Error.WinIOError()
at System.IO.File.InternalMove(String sourceFileName, String destFileName, Boolean checkHost)
at System.IO.File.Move(String sourceFileName, String destFileName)
at UploadAttendanceLogtoSQLTaible.Program.InsertExcelRecords(String filePath, String destinationPath) in C:\Users\**Redacted**\Google Drive\Teaching\Software\UploadAttendanceLog\UploadAttendanceLogtoSQLTable\Program.cs:line 159

The data uploads just fine. It is just moving the file afterwards that is the problem.

Here is the relevant code:
C#:
        private static void InsertExcelRecords(string filePath, string destinationPath)
        {
            LogWriter Log = new LogWriter("");
            try
            {
                //  ExcelConn(_path); 
                string constr = string.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES;""", filePath);
                OleDbConnection Econ = new OleDbConnection(constr);
                string Query = string.Format("Select [Student ID],[Activity],[Session Name],[Date],[Time],[Status],[Sub-Session Name] FROM [{0}]", arg0: "data_RawAttendanceLog$");
                OleDbCommand Ecom = new OleDbCommand(Query, Econ);
                Econ.Open();

                //Create one dataset and fill this data set with this selected items, using oledbdataadpter
                DataSet ds = new DataSet();
                OleDbDataAdapter oda = new OleDbDataAdapter(Query, Econ);
                Econ.Close();
                oda.Fill(ds);
                DataTable Exceldt = ds.Tables[0];

                for (int i = Exceldt.Rows.Count - 1; i >= 0; i--)
                {
                    if (Exceldt.Rows[i]["Student ID"] == DBNull.Value)
                    {
                        Exceldt.Rows[i].Delete();
                    }
                }
                Exceldt.AcceptChanges();

                //creating object of SqlBulkCopy     
                string csDestination = "server = " + GetValueFromFile("server") + "; database = " + GetValueFromFile("database") + "; Trusted_Connection=True"; // User ID = *redacted*; Password = ; Trusted_Connection=True";

                using (SqlConnection con = new SqlConnection(csDestination))
                {

                    SqlBulkCopy objbulk = new SqlBulkCopy(con);
                    //assigning Destination table name     
                    objbulk.DestinationTableName =  GetValueFromFile("DestinationTableName");
                    //Mapping Table column   

                    objbulk.ColumnMappings.Add("[Student ID]", "StudentID");
                    objbulk.ColumnMappings.Add("[Activity]", "Activity");
                    objbulk.ColumnMappings.Add("[Session Name]", "SessionName");
                    objbulk.ColumnMappings.Add("[Date]", "SessionDate");
                    objbulk.ColumnMappings.Add("[Time]", "SessionTime");
                    objbulk.ColumnMappings.Add("[Status]", "SessionStatus");
                    objbulk.ColumnMappings.Add("[Sub-Session Name]", "SubSessionName");

                    //inserting Datatable Records to DataBase   
                    SqlConnection sqlConnection = new SqlConnection();

                    con.Open();
                    objbulk.WriteToServer(Exceldt);

                    Console.WriteLine("Upload successful.");
                    Log.LogWrite("Upload successful.");
                    Econ.Close();
                    Log.LogWrite("Moving " + filePath + " to " + destinationPath);
                    File.Move(filePath, destinationPath);

                }

            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("network-related"))
                {
                    Console.WriteLine("Cancelled. No Network access.");
                    return;
                }
                else
                {
                    Console.WriteLine(string.Format("Upload has not been imported due to: {0}", ex.Message));
                    Log.LogWrite(string.Format("Upload has not been imported due to: {0}", ex.Message));
                    Console.WriteLine("Press any key to close...");
                    ShowWindow(GetConsoleWindow(), SW_SHOW);
                    Console.ReadKey();
                }

            }

        }

    }

Let me know if you need any more information.
Thanks so much.
 
You should compartmentalise your code and break it down into functions with return types and use additional methods. For example, where ever you are executing that code above, you should be allowing the method to execute the statements, and then return to the calling code, where you would and should execute your next method, which should be to remove the excel file you no longer need.

Also, look at all these using statements you can use. Since I don't see where you are disposing of any of your object usage, you stand more chance of narrowing the problem by breaking your code up into sections that perform one task per method/function. :

C#:
                using (OleDbConnection Econ = new OleDbConnection(""))
                {           
                }
                using (OleDbCommand Ecom = new OleDbCommand(Query, Econ))
                {
                }
                using (DataSet ds = new DataSet())
                {
                }
                using (OleDbDataAdapter oda = new OleDbDataAdapter(Query, Econ))
                {
                }
                using (DataTable Exceldt = ds.Tables[0])
                {
                }
Lastly, you should not be trying to remove the file from the same method as that which its principle function was to be used for DB queries, and not deleting files. The error you are getting is because your application is opening that file and therefore can't remove it while its open somewhere else in your code. This is where writing modular self-disposing/reusable code really does help. Start looking at other places where files are being opened, and make sure when a method/function is done using a file, make sure that it is releasing the resources it's used.
 
Just one other thing, which might help you with future development. If you stick to the OOR (Object Orientation Rules) - Just read the articles in the links. Passing around your data, you will find it much more efficient and much easier to avoid issues as this. Go back and review previous code where you are opening this same file.
 
Thanks again. You can probably tell this is my first c# program (which is mostly copied and pasted together from various websites and forums!). I'm more used to using basic.
I have made a few of those changes and will continue to plug away at it until I get get it to work.
I haven't managed to identify another process using the file yet but will also keep trying. EDIT: According to Process Explorer, only this program is using the file.

This is the entire program so far with the SQL table upload code removed along with a sample excel file:


C#:
using System;
using System.IO;
using System.Data.OleDb;
using System.Data;
using System.Data.SqlClient;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;

namespace UploadAttendanceLogtoSQLTable
{

    class Program
    {
        [DllImport("kernel32.dll")]
        static extern IntPtr GetConsoleWindow();

        [DllImport("user32.dll")]
        static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

        const int SW_HIDE = 0;
        const int SW_SHOW = 5;

        static void Main(string[] args)
        {
            ShowWindow(GetConsoleWindow(), SW_HIDE);

            LogWriter Log = new LogWriter("");
            Log.LogWrite("-----------------------------------------------------------");
            Log.LogWrite(DateTime.Now.ToLongTimeString() + " " + DateTime.Now.ToLongDateString());
            Log.LogWrite("Beginning scan and upload of Attendance Logs...");
            Console.WriteLine("Beginning scan and upload of Attendance Logs...");

            string sourceFolder = "C:\\Users\\Name\\Desktop\\Test"; // GetValueFromFile("sourceFolder");
            string destinationFolder = "C:\\Users\\Name\\Desktop\\Test\\Completed"; //  GetValueFromFile("destinationFolder");

            foreach (string filePath in Directory.GetFiles(sourceFolder))
            {
                try
                {
                    string fileExt = System.IO.Path.GetExtension(filePath);
                    string fileName = Path.GetFileName(filePath);
                    string destinationPath = destinationFolder + "\\" + fileName;

                    if (fileExt == ".xlsx")
                    {

                        Console.WriteLine("");
                        Console.WriteLine("Uploading... " + fileName);
                        Log.LogWrite("");
                        Log.LogWrite("Uploading... " + fileName);

                        if (InsertExcelRecords(filePath, destinationPath))
                        {
                            Console.WriteLine("Moving... " + fileName);
                            Log.LogWrite("Moving... " + fileName);
                            try
                            {
                                File.Move(filePath, destinationPath);
                            }
                            catch (Exception ex)
                            {
                                ErrorOccured(ex.Message);
                            }
                        }
                    }
                    else
                    {
                        File.Delete(filePath);
                    }
                }
                catch (Exception ex)
                {
                    ErrorOccured(ex.Message);
                }

            }

            Console.WriteLine("Program Complete");
            Log.LogWrite("Program Complete");
        }


        public static string GetValueFromFile(string valueName)
        {
            string fileValue;
            string[] lines = System.IO.File.ReadAllLines("UploadAttendanceLogtoSQLTableConfig.txt");
            foreach (string line in lines)
            {
                string[] words = line.Split('=');
                if (words[0] == valueName)
                {
                    fileValue = words[1];
                    return fileValue;
                }
            }
            return "N/A";
        }


        public static bool InsertExcelRecords(string filePath, string destinationPath)
        {
            LogWriter Log = new LogWriter("");
            try
            {
                //  ExcelConn(_path);
                string constr = string.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES;""", filePath);
                using (OleDbConnection Econ = new OleDbConnection(constr))
                {
                    string Query = string.Format("Select [Student ID],[Activity],[Session Name],[Date],[Time],[Status],[Sub-Session Name] FROM [{0}]", arg0: "data_RawAttendanceLog$");
                    using (OleDbCommand Ecom = new OleDbCommand(Query, Econ))
                    {

                        Econ.Open();

                        //Create one dataset and fill this data set with this selected items, using oledbdataadpter
                        using (DataSet ds = new DataSet())
                        {
                            using (OleDbDataAdapter oda = new OleDbDataAdapter(Query, Econ))
                            {

                                oda.Fill(ds);
                                using (DataTable Exceldt = ds.Tables[0])
                                {

                                    for (int i = Exceldt.Rows.Count - 1; i >= 0; i--)
                                    {
                                        if (Exceldt.Rows[i]["Student ID"] == DBNull.Value)
                                        {
                                            Exceldt.Rows[i].Delete();
                                        }
                                    }
                                    Exceldt.AcceptChanges();
                                }
                            }
                        }
                    }
                    Econ.Close();
                }
                return true;

            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("network-related"))
                {
                    Console.WriteLine("Cancelled. No Network access.");
                    return false;
                }
                else
                {
                    ErrorOccured(ex.Message);
                    return false;
                }

            }

        }

        private static void ErrorOccured(string errMessage)
        {
            LogWriter Log = new LogWriter("");
            Console.WriteLine(string.Format("The following error occured: {0}", errMessage));
            Log.LogWrite(string.Format("The following error occured: {0}", errMessage));
            Console.WriteLine("Press any key to continue...");
            ShowWindow(GetConsoleWindow(), SW_SHOW);
            Console.ReadKey();
        }

    }



    public class LogWriter
    {
        private string m_exePath = string.Empty;
        public LogWriter(string logMessage)
        {
            LogWrite(logMessage);
        }
        public void LogWrite(string logMessage)
        {
            m_exePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            try
            {
                using (StreamWriter w = File.AppendText(m_exePath + "\\" + "log.txt"))
                {
                    Log(logMessage, w);
                }
            }
            catch (Exception ex)
            {
            }
        }

        public void Log(string logMessage, TextWriter txtWriter)
        {
            try
            {
                txtWriter.WriteLine(DateTime.Now.ToLongTimeString() + " " + logMessage);
            }
            catch (Exception ex)
            {

            }
        }
    }



}
 
Last edited:
I ran your code (changed the paths to be appropriate for my machine) without any issues. The call to File.Move() didn't throw any exceptions. I have 64-bit Office 2019 and Avira.

As a warning to others who may decide to try to copy and paste this code to run. Beware lines 67-70 which will delete files from the sourceFolder.
 
I changed some of the code slightly, and removed a lot of redundant code. But you still have a lot of house keeping to do, and editing. There is so much of the code which needs breaking down and segregate your code into functions and only have one function perform one task, and the same with each method. Currently the code below works, but if you do not delete the file from the destination folder, it will throw an error which you are catching fairly silently, and not actually dealing with why it was raised. Do not catch errors and not handle the issue being presented. That's like the crappiest way to write bad code and as a result you will not know where your problem is should one arise when you publish your application. I can see that you are writing out the issue, but you really ought to handle the issue and not just verbosely log it. So don't do that, unless you are going to handle the issue at first hand.

Change this :
C#:
            foreach (string filePath in Directory.GetFiles(sourceFolder))
            {
                try
                {
                    string fileExt = System.IO.Path.GetExtension(filePath);
                    string fileName = Path.GetFileName(filePath);
                    string destinationPath = destinationFolder + "\\" + fileName;

                    if (fileExt == ".xlsx")
                    {

                        Console.WriteLine("");
                        Console.WriteLine("Uploading... " + fileName);
                        Log.LogWrite("");
                        Log.LogWrite("Uploading... " + fileName);

                        if (InsertExcelRecords(filePath, destinationPath))
                        {
                            Console.WriteLine("Moving... " + fileName);
                            Log.LogWrite("Moving... " + fileName);
                            try
                            {
                                File.Move(filePath, destinationPath);
                            }
                            catch (Exception ex)
                            {
                                ErrorOccured(ex.Message);
                            }
                        }
                    }
                    else
                    {
                        File.Delete(filePath);
                    }
                }
                catch (Exception ex)
                {
                    ErrorOccured(ex.Message);
                }
            }

To This :
C#:
            Create_Folder_Structure(sourceFolder, destinationFolder); bool error = false;
            foreach (string filePath in Directory.GetFiles(sourceFolder))
            {
                try
                {
                    if (Path.GetExtension(filePath) == ".xlsx")
                    {
                        Console.WriteLine(""); string msg = string.Concat("Uploading... ", Path.GetFileName(filePath));
                        Console.WriteLine(msg);
                        Log.LogWrite("");
                        Log.LogWrite(msg);
                        if (InsertExcelRecords(filePath, Path.Combine(destinationFolder, Path.GetFileName(filePath))))
                        {
                            msg = "Moving... " + Path.GetFileName(filePath);
                            Console.WriteLine(msg);
                            Log.LogWrite(msg);
                            File.Move(filePath, Path.Combine(destinationFolder, Path.GetFileName(filePath)));
                        }
                    }
                    else
                    {
                        File.Delete(filePath);
                    }
                }
                catch (IOException nsex)
                {
                    error = true;
                }
                catch (Exception ex)
                {
                    ErrorOccured(ex.Message);
                }
                finally
                {
                    if (error && FileDelete(Path.Combine(destinationFolder, Path.GetFileName(filePath))))
                    {
                        FileMove(filePath, Path.Combine(destinationFolder, Path.GetFileName(filePath)));
                    }
                }
            }
Then add these :
C#:
        private static bool FileMove(string origin, string destination)
        {
            try
            {
                File.Move(origin, destination);
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        private static bool FileDelete(string destination)
        {
            try
            {
                File.Delete(destination);
                return true;
            }
            catch (Exception ex)
            {
                return false;
                //Handle error
            }
        }

        private static void Create_Folder_Structure(string sourceFolder, string destinationFolder)
        {
            if (!Directory.Exists(sourceFolder))
                Directory.CreateDirectory(sourceFolder);
            if (!Directory.Exists(destinationFolder))
                Directory.CreateDirectory(destinationFolder);
        }
Completed you will end up with this :
C#:
using System;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;

namespace UploadAttendanceLogtoSQLTable
{
    internal static class Program
    {
        [DllImport("kernel32.dll")]
        private static extern IntPtr GetConsoleWindow();

        [DllImport("user32.dll")]
        private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

        private const int SW_HIDE = 0;
        private const int SW_SHOW = 5;

        private static void Main(string[] args)
        {
            ShowWindow(GetConsoleWindow(), SW_HIDE);

            LogWriter Log = new LogWriter("");
            Log.LogWrite("-----------------------------------------------------------");
            Log.LogWrite(DateTime.Now.ToLongTimeString() + " " + DateTime.Now.ToLongDateString());
            Log.LogWrite("Beginning scan and upload of Attendance Logs...");
            Console.WriteLine("Beginning scan and upload of Attendance Logs...");

            string sourceFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Test"); // GetValueFromFile("sourceFolder");
            string destinationFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), @"Test\Completed"); //  GetValueFromFile("destinationFolder");
            Create_Folder_Structure(sourceFolder, destinationFolder); bool error = false;
            foreach (string filePath in Directory.GetFiles(sourceFolder))
            {
                try
                {
                    if (Path.GetExtension(filePath) == ".xlsx")
                    {
                        Console.WriteLine(""); string msg = string.Concat("Uploading... ", Path.GetFileName(filePath));
                        Console.WriteLine(msg);
                        Log.LogWrite("");
                        Log.LogWrite(msg);
                        if (InsertExcelRecords(filePath, Path.Combine(destinationFolder, Path.GetFileName(filePath))))
                        {
                            msg = "Moving... " + Path.GetFileName(filePath);
                            Console.WriteLine(msg);
                            Log.LogWrite(msg);
                            File.Move(filePath, Path.Combine(destinationFolder, Path.GetFileName(filePath)));
                        }
                    }
                    else
                    {
                        File.Delete(filePath);
                    }
                }
                catch (IOException nsex)
                {
                    error = true;
                }
                catch (Exception ex)
                {
                    ErrorOccured(ex.Message);
                }
                finally
                {
                    if (error && FileDelete(Path.Combine(destinationFolder, Path.GetFileName(filePath))))
                    {
                        FileMove(filePath, Path.Combine(destinationFolder, Path.GetFileName(filePath)));
                    }
                }
            }

            Console.WriteLine("Program Complete");
            Log.LogWrite("Program Complete");
        }

        private static bool FileMove(string origin, string destination)
        {
            try
            {
                File.Move(origin, destination);
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        private static bool FileDelete(string destination)
        {
            try
            {
                File.Delete(destination);
                return true;
            }
            catch (Exception ex)
            {
                return false;
                //Handle error
            }
        }

        private static void Create_Folder_Structure(string sourceFolder, string destinationFolder)
        {
            if (!Directory.Exists(sourceFolder))
                Directory.CreateDirectory(sourceFolder);
            if (!Directory.Exists(destinationFolder))
                Directory.CreateDirectory(destinationFolder);
        }

        public static string GetValueFromFile(string valueName)
        {
            foreach (var words in from string line in File.ReadAllLines("UploadAttendanceLogtoSQLTableConfig.txt")
                                  let words = line.Split('=')
                                  where words[0] == valueName
                                  select words)
            {
                return words[1];
            }
            return "N/A";
        }

        public static bool InsertExcelRecords(string filePath, string destinationPath)
        {
            LogWriter Log = new LogWriter("");
            try
            {
                using (OleDbConnection Econ = new OleDbConnection(string.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES;""", filePath)))
                {
                    string Query = string.Format("Select [Student ID],[Activity],[Session Name],[Date],[Time],[Status],[Sub-Session Name] FROM [{0}]", arg0: "data_RawAttendanceLog$");
                    using (OleDbCommand Ecom = new OleDbCommand(Query, Econ))
                    {
                        Econ.Open();

                        //Create one dataset and fill this data set with this selected items, using oledbdataadpter
                        using (DataSet ds = new DataSet())
                        {
                            using (OleDbDataAdapter oda = new OleDbDataAdapter(Query, Econ))
                            {
                                oda.Fill(ds);
                                using (DataTable Exceldt = ds.Tables[0])
                                {
                                    for (int i = Exceldt.Rows.Count - 1; i >= 0; i--)
                                    {
                                        if (Exceldt.Rows[i]["Student ID"] == DBNull.Value)
                                        {
                                            Exceldt.Rows[i].Delete();
                                        }
                                    }
                                    Exceldt.AcceptChanges();
                                }
                            }
                        }
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("network-related"))
                {
                    Console.WriteLine("Canceled. No Network access.");
                    return false;
                }
                else
                {
                    ErrorOccured(ex.Message);
                    return false;
                }
            }
        }

        private static void ErrorOccured(string errMessage)
        {
            LogWriter Log = new LogWriter("");
            Console.WriteLine(string.Format("The following error occured: {0}", errMessage));
            Log.LogWrite(string.Format("The following error occured: {0}", errMessage));
            Console.WriteLine("Press any key to continue...");
            ShowWindow(GetConsoleWindow(), SW_SHOW);
            Console.ReadKey();
        }
    }

    public class LogWriter
    {
        private string m_exePath = string.Empty;

        public LogWriter(string logMessage) => LogWrite(logMessage);

        public void LogWrite(string logMessage)
        {
            m_exePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            try
            {
                using (TextWriter txt_Writer = File.AppendText(Path.Combine(m_exePath, "log.txt")))
                    txt_Writer.WriteLine(string.Concat(DateTime.Now.ToLongTimeString(), string.Empty.PadRight(1), logMessage));
            }
            catch (Exception ex)
            {
            }
        }

        public void Log(string logMessage, TextWriter txtWriter)
        {
            try
            {
                using (txtWriter)
                    txtWriter.WriteLine(string.Concat(DateTime.Now.ToLongTimeString(), string.Empty.PadRight(1), logMessage));
            }
            catch (Exception ex)
            {
            }
        }
    }
}
Just as an aside note, while this does fix your error, you still need to tidy your code, and fix up some typos in your grammar as well as what i said on post 17. Your problem was, that you were not checking if a file already existed in the destination folder, and if the file was ever moved to the completed directory, and upon trying to move the same filename to that directory, you were receiving the IO error as a result. The code I changed resolves this and some other minor issues.
 
@Sheepings makes several good points about error handling (particularly the existing file case).

The point I was trying to make with my post #19 was that I was not getting the exception regarding the file being opened by another process while trying to do a file move. At first I thought it was because of the way the OP was doing his exception and error handling, so I specifically sent breakpoints and enabled first-chance exceptions just in case I was missing something. I never got the file open exception. I would get the file exists exception, but the exception was pretty clear about the the destination existing, rather than the file being open.
 
@Sheepings Thanks so much. I'm taking on board what you are saying about error handling. I think because the program will only be run by me on my computer, I didn't handle all the exceptions like I should. Unfortunately though, I still get the same error with your code.

@Skydiver Thank you for checking.

Given that the code works fine for both of you, all I can think of is that it must be something specific to my environment, perhaps as a result of reinstalling Office 365.
 
It sounds like you work for a company that has pretty tight locked down systems. Work with you IT security team. Have them isolate a single system and disable the AV for 5 minutes while you do a test run. If it works with AV disabled, and then fails again with AV enabled, have them contact the vendor to try to work with you to debug why.

If AV on or off doesn't make a difference, next work with your desktop image team. See if they will let you setup three VMs that are not actively attached to your work network. In one VM have their current desktop image. In the second, their desktop image from a year ago. In the third, a vanilla installation of Win10 and Office without any of their customizations. Those three different images should help you narrow down where the point of failure is.

As you'll note with my first paragraph above, I'm sort of leaning on the AV software being my prime suspect, but it could also be a bug in the updates sent out by Microsoft. MS has not had a good track record over the past two years with regards to introducing regressions with their patches and updates.
 
It sounds like you work for a company that has pretty tight locked down systems. Work with you IT security team. Have them isolate a single system and disable the AV for 5 minutes while you do a test run. If it works with AV disabled, and then fails again with AV enabled, have them contact the vendor to try to work with you to debug why.

If AV on or off doesn't make a difference, next work with your desktop image team. See if they will let you setup three VMs that are not actively attached to your work network. In one VM have their current desktop image. In the second, their desktop image from a year ago. In the third, a vanilla installation of Win10 and Office without any of their customizations. Those three different images should help you narrow down where the point of failure is.

As you'll note with my first paragraph above, I'm sort of leaning on the AV software being my prime suspect, but it could also be a bug in the updates sent out by Microsoft. MS has not had a good track record over the past two years with regards to introducing regressions with their patches and updates.

Thank you. Yeah, I feel like it might be the AV. However, even 30 seconds after the file is supposedly closed, it still won't move.
I went and spoke to someone in IT today and given the nature of the department, I could be waiting a while to get this sorted.

In the meantime, I got around the issue with a not-so-elegent work around.

Instead of:
1) Open each file in the source folder and upload its contents to the table
2) If successful, move the file to the 'Completed' folder

I have created a new folder called 'Processing' and got the following to work:
1) Delete all files in the 'Processing' folder
2) Copy any files from the source folder to the 'Processing' folder
3) Open the files in the 'Processing' folder and upload their contents to the table
4) If successful, move the files from the source folder to the 'Completed' folder

This way, because the files in the source folder aren't actually being opened, File.Move is successful.
The files that are being opened (in the 'Processing' folder) get deleted on the next program run.

Thanks for the help guys.
 
Hi Kris,
I got a similar problem trying to delete an excel file, throwing the same exception.
Reinstalling the microsoft database engine did the trick.

Can you try it?
 
The Microdoft Access Database Engine?
Hi Kris,
I got a similar problem trying to delete an excel file, throwing the same exception.
Reinstalling the microsoft database engine did the trick.

Can you try it?

Hi KoenHoof,

Unfortunately, I can't verify if that would have fixed the issue as I had to get a complete reimage. However, after the reimage and reinstallation of the database engine, file.move now does work as expected.
 
On a side note; relating to the code I previously posted. When I posted it, I actually focused more on the error of what would happen if the destination file already existed and what to do with it if it did, that I got a little side-tracked and never finished writing out the bit for handing the error of the file being already in-use. Thanks @Skydiver for pointing that out to me off the board, I still haven't had time to edit it, but its nice to see that you guys resolved it buy blaming Microsoft on creating yet another bug which you's resolved yourselves. (y)
 

Latest posts

Back
Top Bottom