栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

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

1:Win7可以,WIN10不可以

try 
    { 
     //原理,如果文件可以被移动,说明未被占用 
     string strPath = "C:\123OK.Excel"; 
     string strPath2 = "C:\123OK22.Excel"; 
     File.Move(strPath, strPath2); 
     File.Move(strPath2, 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; 
   } 
  } 
 } 
} 

 感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/146595.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号