/// This is my code and my file already open in window i want to close it first and then delete pls help

var directory = new DirectoryInfo(path);

                {
                    if (!IsFileLocked(file1, file) & file1.Name == file + ".xlsx")
                        File.Delete(path + file + ".xlsx"); // DELETE THE FILE BEFORE CREATING A NEW ONE.
                }


  public static Boolean IsFileLocked(FileInfo file, string fileName)
    {
        FileStream stream = null;
        try
        {
            if (file.Name == fileName + ".xlsx")
            {
                using (stream = File.Open(file.FullName, FileMode.Open, FileAccess.Write, FileShare.Read))
                {
                }                
            }
        }
        catch (Exception ex)
        {
            return true;
        }
        finally
        {
            if (stream != null)
                stream.Close();
        }
        return false;
    }

Did you try to save the excel file first?

It's probably a timing issue. I've encountered similar issues when things happen too fast between closing the file and trying to delete it. A workaround would be to retry the deletion a few times after a short pause:

public static bool SafeDelete(string path, int tries = 1, int wait = 300, bool throwOnFail = false)
{
    // Sanitize the retries count
    if (tries < 1)
    {
        tries = 1;
    }

    for (int i = 0; i < tries; i++)
    {
        try
        {
            if (File.Exists(path))
            {
                File.Delete(path);
            }

            return true;
        }
        catch
        {
            if (i < tries - 1)
            {
                Thread.Sleep(wait);
            }
            else
            {
                if (throwOnFail)
                {
                    throw;
                }
            }
        }
    }

    return false;
}

I can't figure out how to preview this post or what Dani did with code tags. I'll let the mods sort that out.

My thoughts:

You have a few problems
1) You didn't post complete code
2) The 4th argument of File.Open() you have FileShare.Read. You need exclusive file access to delete so you should use FileShare.None.
3) You declare 'stream' as null but instantiate it in a using block. 'using' takes care of disposal so you have a lot of unnecessary code.
4) In your catch statement you "catch (Exception ex)" -- but never use the exception. Just "catch" without naming will do.
5) You didn't specify if your code opens the excel file. This is a critical design consideration. See OpenExcelFileThenDelete()
6) If #5 does not apply then see the FileSystemWatcher code. TAKE NOTE that Excel uses hidden temp files when saving changes. So if you put a watcher on the exact file name you will NOT get all change notifications.
7) If this is on a network drive ... then .... have fun. Many more issues.
8) To deceptikon's comment about timing -- this could very well be true. Almost all instances where I found this to be true had to deal with antivirus "real-time" scanning. It has to open the file to inspect it, thus causing the file in use problem. Side note: this is why you should never run 2 real-time AV scanners. They just step on one another.

using System;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;

namespace daniweb
{
    sealed partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        void button1_Click(object sender, EventArgs e)
        {
            OpenExcelFileThenDelete();
        }

        bool OpenExcelFileThenDelete()
        {
            const string fname = @"C:\dw.xlsx";
            using (Process p = Process.Start(fname))
            {
                p.WaitForExit();
            }
            try
            {
                File.Delete(fname);
                return true;
            }
            catch
            {
                return false;
            }
        }

        //This is instantiated and events are wired up when creating the form. You need to handle that, and dispose of the FSW.
        FileSystemWatcher m_fsw = new FileSystemWatcher(@"C:\")
        {
            EnableRaisingEvents = true,
        };

        void DeleteFile(string fname)
        {
            //Delete the file here
            //MessageBox.Show("FIRE");
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            m_fsw.Changed += m_fsw_Changed;
        }

        void m_fsw_Changed(object sender, FileSystemEventArgs e)
        {
            DeleteFile(e.FullPath);
        }
    }
}

Hé! sknake! You're back, and as always with comments showing deep knowledge. :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.