Skip to content

Instantly share code, notes, and snippets.

@ramonsmits
Created November 30, 2023 12:19
Show Gist options
  • Save ramonsmits/ec4aa2eb1a3c132e76f68eff9bc9f810 to your computer and use it in GitHub Desktop.
Save ramonsmits/ec4aa2eb1a3c132e76f68eff9bc9f810 to your computer and use it in GitHub Desktop.
Check if a file is in use by trying to open it exclusively
static class FileHelper
{
public static bool FileInUse(string path)
{
try
{
using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.None);
return false;
}
catch (IOException)
{
// If file does not exist, it's not in use
return File.Exists(path);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment