A191919 A191919 - 3 months ago 30
C# Question

C# check file that used by process

Let i have program that open file and append something.
If i should run two apllication i will get IOException file used by another process. How it's possible to check that file Log.txt is using by another process?

class Program
{
static void Main(string[] args)
{
FileInfo file = new FileInfo(@"D:\Log.txt");
using (StreamWriter sw = file.AppendText())
{
for (int i = 0; i < 1000; i++)
{
System.Threading.Thread.Sleep(100);
sw.WriteLine("Hello");
sw.WriteLine("And");
sw.WriteLine("Welcome");
}
Console.WriteLine("The work is done");
}
}
}

sam sam
Answer

You should try to open and write to the file. If it is in use you get an exception. No other way in .NET.

protected virtual bool IsFileLocked(FileInfo file)
{
    FileStream stream = null;

    try
    {
        stream = file.Open(FileMode.Open, FileAccess.Read, 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;
}
Comments