我有一个excel文件,有2个独立的C#程序都要对其进行读写操作。
由于2个C#程序相互独立,无法判断对excel读写时,另一个是否也在读写excel。
请教一下,一个程序如何在操作前,得知excel正被另一个程序操作呢?

解决方案 »

  1.   

    try
    catch进入catch,并且ex.Message里有进程错误,就说明被别的进程打开了
      

  2.   

    public static bool IsFileInUse(string filePath)
    {
        if (!File.Exists(filePath))
        {
            return false;
        }    SafeHandle handleValue = null;    try
        {
            handleValue = FileHelper.CreateFile(filePath, FileHelper.GENERIC_WRITE, 0, IntPtr.Zero, FileHelper.OPEN_EXISTING, 0, IntPtr.Zero);        bool inUse = handleValue.IsInvalid;        return inUse;
        }
        finally
        {
            if (handleValue != null)
            {
                handleValue.Close();            handleValue.Dispose();            handleValue = null;
            }
        }
    }
      

  3.   

    Add[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
    private static extern Microsoft.Win32.SafeHandles.SafeFileHandle CreateFile(string lpFileName, System.UInt32 dwDesiredAccess, System.UInt32 dwShareMode, IntPtr pSecurityAttributes, System.UInt32 dwCreationDisposition, System.UInt32 dwFlagsAndAttributes, IntPtr hTemplateFile);private static readonly uint GENERIC_WRITE = 0x40000000;
    private static readonly uint OPEN_EXISTING = 3;