Directory.Delete(path,true) the file is being used by another process

时间:2018-09-18 20:10:51

标签: c# .net directory filesystems

I have a function that should check a directory's files, and if it finds a file with a specific name it should delete the directory (kinda like a cleaning job)

public static void consumeFolderFiles(string path) 
{
    // get directory info
    DirectoryInfo info = new DirectoryInfo(path);

    // I want the files to be in order because I am planning to send them via FTP in order in the future.
    FileInfo[] files = info.GetFiles().OrderBy(p => p.CreationTime).ToArray();
    bool success = false;

    if (files.Length > 0) 
    {
        // FTP logic (not implemented yet)
        // Check if there's a file's name that contains "balance"
        success = files.FirstOrDefault(f => f.Name.ToLower().Contains("balance")) != null;

        // Check if it's time to delete the directory 
        if (success) 
        {
            Directory.Delete(path, true);
        }
    }
    else 
    {
        // Custom exception 
        throw new NoNewTransactionsInFolderException();
    }
}

This function seems to be working, but occasionally I get the exception "the process cannot access the file ****.*** because it's being used by another process".Also, I noticed that all the files before the exception got deleted normally.

The function throws the exception inconsistently. Which means it might delete the folder or stop somewhere in the middle. Thus, I don't think I forgot closing a resource or a handler.

I think it's a good idea to include the file creating function. I might missed something there.

public static void createXMLFile(object o, string path, string fileName) 
{
    XmlSerializer xml = new XmlSerializer(o.GetType());

    XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
    ns.Add("", "");

    XmlTextWriter xtw = new XmlTextWriter(Path.Combine(path, fileName), Encoding.UTF8);
    xtw.Formatting = Formatting.Indented;

    xml.Serialize(xtw, o, ns);

    xtw.Close();
    xtw.Dispose();
}

I have seen other answers where people suggested adding a try catch and call Directory.Delete(path,true) in the catch clause, or using .NET Transactional File Manager. However, I would like to know the reason of this exception. Is it something I am doing wrong or an OS bug?

0 个答案:

没有答案