In C three methods are used to determine if Excel is being imported

  • 2020-07-21 08:13:45
  • OfStack

In C#, there are three ways to determine if Excel imports are being used

There are three ways to determine whether Excel is occupied when importing:

1: Win7 is ok,WIN10 is not


try 
    { 
     // Principle, if the file can be moved, it is not occupied  
     string strPath = "C:\\123OK.Excel"; 
     string strPath2 = "C:\\123OK22.Excel"; 
     File.Move(strPath, strPath2); 
     File.Move(strPath2, strPath); 
    } 
    catch 
    { 
     MessageBox.Show(" The file is occupied! "); 
     return; 
    } 

2: File flow


try 
    { 
     // Principle, if the file is writable, the description is not occupied  
     System.IO.FileStream stream = System.IO.File.OpenWrite(" The file path "); 
     stream.Close(); 
    } 
    catch 
    { 
     MessageBox.Show(" The file is occupied! "); 
     return; 
    } 

3: WIN32 API call (strongly recommended)


using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 
 
using System.IO; 
using System.Runtime.InteropServices; 
 
namespace WindowsFormsApplication1 
{ 
 public partial class Form1 : Form 
 { 
  [DllImport("kernel32.dll")] 
  public static extern IntPtr _lopen(string lpPathName, int iReadWrite); 
  [DllImport("kernel32.dll")] 
  public static extern bool CloseHandle(IntPtr hObject); 
  public const int OF_READWRITE = 2; 
  public const int OF_SHARE_DENY_NONE = 0x40; 
  public readonly IntPtr HFILE_ERROR = new IntPtr(-1); 
 
  public Form1() 
  { 
   InitializeComponent(); 
  } 
 
  private void button1_Click(object sender, EventArgs e) 
  { 
   try 
   { 
    string vFileName = @"c:\123.xlsx"; 
    if (!File.Exists(vFileName)) 
    { 
     MessageBox.Show(" The file doesn't exist !"); 
     return; 
    } 
    IntPtr vHandle = _lopen(vFileName, OF_READWRITE | OF_SHARE_DENY_NONE); 
    if (vHandle == HFILE_ERROR) 
    { 
     MessageBox.Show(" The file is occupied! "); 
     return; 
    } 
    CloseHandle(vHandle); 
    MessageBox.Show(" It's not occupied! "); 
   } 
   catch (Exception ex) 
   { 
    throw ex; 
   } 
  } 
 } 
} 

Thank you for reading, I hope to help you, thank you for your support to this site!


Related articles: