使用C# 导入Excel文件时如何实现判断是否被占用

发布时间:2020-11-17 16:28:14 作者:Leah
来源:亿速云 阅读:355

使用C# 导入Excel文件时如何实现判断是否被占用?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

C# 中Excel导入时 判断是否被占用三种方法

Excel导入时 判断是否被占用,三种方法:

1:Win7可以,WIN10不可以

try 
    { 
     //原理,如果文件可以被移动,说明未被占用 
     string strPath = "C:\\123OK.Excel"; 
     string strPath3 = "C:\\123OK22.Excel"; 
     File.Move(strPath, strPath3); 
     File.Move(strPath3, strPath); 
    } 
    catch 
    { 
     MessageBox.Show("文件被占用!"); 
     return; 
    } 

2:文件流

try 
    { 
     //原理,如果文件可写,说明未被占用 
     System.IO.FileStream stream = System.IO.File.OpenWrite("文件路径"); 
     stream.Close(); 
    } 
    catch 
    { 
     MessageBox.Show("文件被占用!"); 
     return; 
    } 

3:WIN32 API调用(强烈推荐)

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("文件都不存在!"); 
     return; 
    } 
    IntPtr vHandle = _lopen(vFileName, OF_READWRITE | OF_SHARE_DENY_NONE); 
    if (vHandle == HFILE_ERROR) 
    { 
     MessageBox.Show("文件被占用!"); 
     return; 
    } 
    CloseHandle(vHandle); 
    MessageBox.Show("没有被占用!"); 
   } 
   catch (Exception ex) 
   { 
    throw ex; 
   } 
  } 
 } 
} 

关于使用C# 导入Excel文件时如何实现判断是否被占用问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。

推荐阅读:
  1. 使用Python制作自动推送微信消息提醒的备忘录功能
  2. C#获取Excel第一列的实例方法

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

excel

上一篇:使用ftpClient如何实现下载ftp文件解析

下一篇:Java中final、finally和finalize关键字有什么不同的地方

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》