I am trying to determine whether or not a file is currently open or being written to using C#. I've seen similar SO questions, all with a similar solution as my code, which attempts a File.Open on a file. But when I run the program with the code below, and I also manually have the file open, I get the unexpected result of "File is currently NOT locked". Any thoughts/suggestions/anything I'm missing?
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Threading; namespace TestIfFileAccessed { class Program { static void Main(string[] args) { string path = @"C:\TEMP\testFile.txt"; FileInfo filepath = new FileInfo(path); if (IsFileLocked(filepath)) { Console.WriteLine("File is currently locked"); Console.ReadLine(); } else { Console.WriteLine("File is currently NOT locked"); Console.ReadLine(); } } public static bool IsFileLocked(FileInfo file) { FileStream stream = null; try { stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None); } 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; } finally { if (stream != null) stream.Close(); } //file is not locked return false; } } }
using(...)statement on thatfile.Open().stream.Dispose()does thatstream.Close()doesn't already do?FileInfo.Openand don't close it. Give it a try :)