using System;
using System.IO;
using System.Runtime.InteropServices;

namespace GcDevicePc.Common
{
    class FileTools
    {
        [DllImport("kernel32.dll")]
        public static extern IntPtr _lopen(string lpPathName, int iReadWrite);

        [DllImport("kernel32.dll")]
        public static extern bool CloseHandle(IntPtr hObject);

        private const int OF_READWRITE = 2;
        private const int OF_SHARE_DENY_NONE = 0x40;
        private readonly IntPtr HFILE_ERROR = new IntPtr(-1);

        public int IsUse(String path )
        {
            if (!File.Exists(path)){
                return 1;
            }

            IntPtr vHandle = _lopen(path, OF_READWRITE | OF_SHARE_DENY_NONE);

            if (vHandle == HFILE_ERROR){
                return 2;
            }

            CloseHandle(vHandle);
            return 0;
        }
    }
}
