C# 中Excel導(dǎo)入時判斷是否被占用三種方法
更新時間:2017年04月23日 16:33:35 投稿:lqh
這篇文章主要介紹了C# 中Excel導(dǎo)入時 判斷是否被占用三種方法的相關(guān)資料,需要的朋友可以參考下
C# 中Excel導(dǎo)入時 判斷是否被占用三種方法
Excel導(dǎo)入時 判斷是否被占用,三種方法:
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調(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("沒有被占用!"); } catch (Exception ex) { throw ex; } } } }
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
Java?循環(huán)隊(duì)列/環(huán)形隊(duì)列的實(shí)現(xiàn)流程
循環(huán)隊(duì)列又叫環(huán)形隊(duì)列,是一種特殊的隊(duì)列。循環(huán)隊(duì)列解決了隊(duì)列出隊(duì)時需要將所有數(shù)據(jù)前移一位的問題。本文將帶大家詳細(xì)了解循環(huán)隊(duì)列如何實(shí)現(xiàn),需要的朋友可以參考一下2022-02-02在SpringBoot框架下實(shí)現(xiàn)Excel導(dǎo)入導(dǎo)出的方法詳解
SpringBoot是由Pivotal團(tuán)隊(duì)提供的全新框架,其設(shè)計目的是用來簡化新Spring應(yīng)用的初始搭建以及開發(fā)過程,今天我們就使用純前對按表格控件帶大家了解,如何在Spring Boot框架下實(shí)現(xiàn)Excel服務(wù)端導(dǎo)入導(dǎo)出,需要的朋友可以參考下2023-06-06