Click here to Skip to main content
15,889,877 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
I am not expert. I am trying to delete the files from the directory at button click. I have windows application which have folders populated in combobox1 and files populated in combobox2. I need to delete the selected folder from combobox1 and files within the folder. I am getting error cannot delete the file as it's being used by another process. Basically application can be used by multiple users and one of the folder I am trying to delete might be listed on the second users combobox. I need to delete the files even if its listed in second users combobox, as I have another logic that doesn't allow the user to select the combobox item selected by first user.

The error is caused because of same filename in another folder(As I have images in all the folders with same names, but different images), it's not caused due to the folder being tried to delete. If user selects the batch that's already deleted, I have logic in place to check if that particular directory no longer exists remove from combobox and move to next batch or first batch if deleted item was last one.

C#
    string batchrem = "";
    selindex02 = comboBox1.SelectedIndex;
    batchrem = comboBox1.Text;

    string dir_name = comboBox1.Text.ToString().Substring(0, 12);
    string path1 = strval + dir_name + "\\";
    //string path1 ="C:\\Project\\" + dir_name + "\\";
    DirectoryInfo di = new DirectoryInfo(path1);
    SqlConnection conn001 = new SqlConnection();
    conn001.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["dbConnection"].ConnectionString;
    SqlCommand comd012 = new SqlCommand("GetBatch", conn001);
    comd012.CommandType = CommandType.StoredProcedure;
    comd012.CommandText = "usp_CAMR_Delete_MarriageInfo";
    comd012.Connection = conn001;
    comd012.Parameters.AddWithValue("@batch_name", comboBox1.Text.ToString().Substring(0, 12));
    comd012.Parameters.AddWithValue("@ERR_CODE", 0);
    comd012.Parameters.AddWithValue("@ERR_MSG", 0);
    comd012.Parameters.AddWithValue("@TABLE_NAME", "");
    try
    {
        SqlConnection con = new SqlConnection();
        con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["dbConnection"].ConnectionString;
        SqlCommand cmd = new SqlCommand("BatchUpdate", con);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.CommandText = "usp_CAMR_UnlockedBatchName";
        //cmd.Connection = con;
        con.Open();
        cmd.Parameters.AddWithValue("@Batch_Name", comboBox1.Text.ToString().Substring(0, 12));
        cmd.Parameters.AddWithValue("@lst_mod_userid", Environment.UserName);
        cmd.Parameters.AddWithValue("@ERR_CODE", 0);
        cmd.Parameters.AddWithValue("@ERR_MSG", 0);
        cmd.Parameters.AddWithValue("@TABLE_NAME", 0);
        cmd.ExecuteNonQuery();
        con.Close();
        con.Dispose();
        conn001.Open();
        comd012.ExecuteNonQuery();
    }
    catch (Exception ex)
    {
        {
            oErrorLog.WriteErrorLog(ex.ToString());
        }
        lblerror.Text = "Please contact support team";
    }
    finally
    {
        conn001.Close();
        conn001.Dispose();
        if (di.Exists)
        {
            try
            {
                if (comboBox1.SelectedIndex < comboBox1.Items.Count - 1)
                {
                    comboBox1.SelectedIndex = selindex02 + 1;
                }
                else
                {
                    // comboBox1.Items.Remove(batchrem);
                    comboBox1.SelectedIndex = 0;
                }
                foreach (FileInfo fi in di.GetFiles())
                {

                    System.GC.Collect();
                    System.GC.WaitForPendingFinalizers();
                    fi.IsReadOnly = false;
                    fi.Delete();
                }
                di.Delete();
                comboBox1.Items.Remove(batchrem);
            }
            catch (Exception ex)
            {

                lblerror.Text = ex.Message();
            }
        }
    }
}


What I have tried:

I tried using
System.GC.Collect();
System.GC.WaitForPendingFinalizers();


It works fine if there is only one user using the application
Posted
Updated 15-Jun-18 5:25am
v5
Comments
kaooodate 13-Dec-19 3:22am    
Work for me, thank you

Like the error says, you cannot delete a file that is in use by any process nor can you delete a folder which has a file open in it.

The comboboxes have nothing at all to do with this. They are just containers that show a string, in your case a file/folder name.

The files are actually in use by some process. You cannot delete them until the every process that has the file open closes it.

Yes, it is POSSIBLE to delete a file that is in use, BUT, there are consequences to doing so. You WILL cause the application that had the file open to crash and you WILL cause system instability, leading Windows to eventually crash.
 
Share this answer
 
Comments
Member 12076824 1-Feb-17 11:48am    
The error is caused because of same filename in another folder(As I have images in all the folders with same names), it's not caused due to the folder being tried to delete. About the application crashing I have logic in place to check if that particular directory no longer exists remove from combobox and move to next batch or first batch if deleted item was last one.
Dave Kreskowiak 1-Feb-17 12:44pm    
In the context of your original post, your comment made absolutely no sense at all.
Member 12076824 1-Feb-17 13:06pm    
I realized that today, I added that to the question as well. Thanks for your response
Rob Philpott 1-Feb-17 12:06pm    
That's interesting. How would one delete a file in use by another process?
Dave Kreskowiak 1-Feb-17 12:45pm    
I'm not saying. The real "I gotta have" people will Google for it.
Just a warning, it ain't pretty.
You can have them deleted on reboot. You'll need the P/Invoke declarations for MoveFileEx:

[Flags]
internal enum MoveFileFlags
{
    None = 0,
    ReplaceExisting = 1,
    CopyAllowed = 2,
    DelayUntilReboot = 4,
    WriteThrough = 8,
    CreateHardlink = 16,
    FailIfNotTrackable = 32,
}

internal static class NativeMethods
{
    [DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Unicode)]
    public static extern bool MoveFileEx(
        string lpExistingFileName,
        string lpNewFileName, 
        MoveFileFlags dwFlags);
}

if (!NativeMethods.MoveFileEx("a.txt", null, MoveFileFlags.DelayUntilReboot))
{
    Console.Error.WriteLine("Unable to schedule 'a.txt' for deletion");
}
 
Share this answer
 
You can, but it has to be done on reboot, so you are wrong. There is also a way to force, and this is known because there is an application out there that will delete even locked files: IObit Unlocker, Solution for "undelete files or folders" Problems on Windows 8, 7, Vista, XP, 10 - IObit[^]
 
Share this answer
 
Comments
Richard Deeming 15-Jun-18 11:51am    
Really? Two new solutions to a question from 18 months ago?

Solution 3 was a good addition, but was there really a need to post a second solution?
Quote:
I am getting error cannot delete the file as it's being used by another process.
Short answer: No, you can't, windows will not allow it.
 
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