Home > Mobile >  skipping files while deleting that are currently in use
skipping files while deleting that are currently in use

Time:07-28

i try to make a temp cleaner and the program it self works but how can i write the programm that it skips the files that are currently in use?

here is the script i used

System.IO.DirectoryInfo di = new DirectoryInfo(path);

    foreach (FileInfo file in di.GetFiles())
    {
        file.Delete(); 
    }
    foreach (DirectoryInfo dir in di.GetDirectories())
    {
        dir.Delete(true); 
    }

CodePudding user response:

ok so i made it like that:

protected virtual bool IsFileLocked(FileInfo file try { using(FileStream stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.None)) { System.IO.DirectoryInfo di = new DirectoryInfo(path);

    foreach (FileInfo file in di.GetFiles())
    {
        file.Delete(); 
    }
    foreach (DirectoryInfo dir in di.GetDirectories())
    {
        dir.Delete(true); 
    }
        stream.Close();
        Console.WriteLine("finished!");
        Console.WriteLine("Press any key to exit...");
        Console.ReadKey();
    }
}
catch (IOException)
{
    return false;
}

but it still gave me errors

CodePudding user response:

protected virtual bool IsFileLocked(FileInfo file)
{
    try
    {
        using(FileStream stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.None))
        {
            stream.Close();
        }
    }
    catch (IOException)
    {
        //the file is unavailable because it is:
        //still being written to
        //or being processed by another thread
        //or does not exist (has already been processed)
        return true;
    }

    //file is not locked
    return false;
}

Original post: Is there a way to check if a file is in use?

  • Related