Excel导入时 判断是否被占用
2017-03-22 17:42
567 查看
Excel导入时 判断是否被占用,三种方法:
1:Win7可以,WIN10不可以
2:文件流
3:WIN32 API调用(强烈推荐)
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; } } } }
相关文章推荐
- C# 中Excel导入时判断是否被占用三种方法
- Excel操作Bug引出的问题:如何判断文件是否被占用、打开
- 使用反射,在Excel导入时判断是否有空行
- 导入时判断数据位数是否符合要求
- 如何在excel中判断某个单元格的值是否在某列中存在?
- EXCEL 判断一个单元格中是否有图片
- 如何判断Excel文件是否打开
- [导入]判断输入是否为中文的函数
- C#判断文件是否被打开占用
- [导入]sqlserver 判断临时表是否存在语句.
- [导入]判断学号前十位的年龄最大的女学生是否是汉族的
- 判断机器是否有安装excel
- 我是否可以将Excel数据导入?
- 判断一个文件是否被占用
- EXCEL 公式使用小计 生成sql 语句 判断某一数据是否在另一列中出现
- 判断上传文件是否是Excel文件
- [导入]实现删除主表数据时, 判断与之关联的外键表是否有数据引用, 有标志, 无则删除
- 关于javascript如何判断某个字符是否占用两个字符的讨论
- 判断Excel单元格是否处于编辑状态
- QTP中如何判断Excel进程是否存在?