C# 中Excel導(dǎo)入時(shí)判斷是否被占用三種方法
更新時(shí)間:2017年04月23日 16:33:35 投稿:lqh
這篇文章主要介紹了C# 中Excel導(dǎo)入時(shí) 判斷是否被占用三種方法的相關(guān)資料,需要的朋友可以參考下
C# 中Excel導(dǎo)入時(shí) 判斷是否被占用三種方法
Excel導(dǎo)入時(shí) 判斷是否被占用,三種方法:
1:Win7可以,WIN10不可以
try
{
//原理,如果文件可以被移動(dòng),說(shuō)明未被占用
string strPath = "C:\\123OK.Excel";
string strPath2 = "C:\\123OK22.Excel";
File.Move(strPath, strPath2);
File.Move(strPath2, strPath);
}
catch
{
MessageBox.Show("文件被占用!");
return;
}
2:文件流
try
{
//原理,如果文件可寫(xiě),說(shuō)明未被占用
System.IO.FileStream stream = System.IO.File.OpenWrite("文件路徑");
stream.Close();
}
catch
{
MessageBox.Show("文件被占用!");
return;
}
3:WIN32 API調(diào)用(強(qiáng)烈推薦)
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("沒(méi)有被占用!");
}
catch (Exception ex)
{
throw ex;
}
}
}
}
感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!
相關(guān)文章
java實(shí)現(xiàn)區(qū)域內(nèi)屏幕截圖示例
這篇文章主要介紹了java截圖示例,需要的朋友可以參考下2014-04-04
spring boot security設(shè)置忽略地址不生效的解決
這篇文章主要介紹了spring boot security設(shè)置忽略地址不生效的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-07-07
arthas排查jvm中CPU占用過(guò)高問(wèn)題解決
這篇文章主要介紹了arthas排查jvm中CPU占用過(guò)高問(wèn)題解決,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09
MyBatis實(shí)戰(zhàn)之Mapper注解的示例
本文主要介紹了MyBatis實(shí)戰(zhàn)之Mapper注解的示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2024-10-10

