简体   繁体   中英

Check if file is being used before moving it

I am playing a *.mp4 file in media player but at the same time trying to move the file from one place to another I need to check if the file is being accessed by another process i want to block the move process.

public Boolean fileInUse(FileInfo file)
{
    FileStream stream=null;
    try
    {
        stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.None);

    }
    catch (IOException)
    {
        //File is in use
        Console.WriteLine("File is Being used");
        return true;
    }
    finally {
        if (stream != null) {
            stream.Close();
        }
    }
    Console.WriteLine("File is not in use");
    return false;    
}
public Boolean fileInUse(FileInfo file)
{
    bool fileInUse = false;
    FileStream stream = null;
    try
    {
        stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.None);
        stream.Close();
    }
    catch (IOException)
    {
        //File is in use
        Console.WriteLine("File is Being used");
        fileInUse = true;
    }

    Console.WriteLine("File is not in use");
    return fileInUse;    
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM