Tuesday, August 16, 2011

How to check file is in use in C#.Net


Program to check file is in use in C#.Net:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;

namespace CreateAndReadXMLFileByManishAgrahari
{


    class Employee
    {
       

        static void Main(string[] args)
        {
            Employee objEmp = new Employee();
            Boolean isFileInUse = objEmp.IsFileLocked(new FileInfo(@"C:\\Manish_Agrahari.txt"));
            if (isFileInUse)
            {
                Console.WriteLine("File is in use.");
            }
            else
            {
                Console.WriteLine("File is in not use.");
            }

            Console.ReadLine();
        }

        public 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;
        }
    }
}


0 comments: