1:Win7可以,WIN10不可以
?
1
2
3
4
5
6
7
8
9
10
11
12
13
|
try
{
//原理,如果文件可以被移动,说明未被占用
string strPath = "C:\\\\123OK.Excel" ;
string strPath2 = "C:\\\\123OK22.Excel" ;
File.Move(strPath, strPath2);
File.Move(strPath2, strPath);
}
catch
{
MessageBox.Show( "文件被占用!" );
return ;
}
|
2:文件流
?
1
2
3
4
5
6
7
8
9
10
11
|
try
{
//原理,如果文件可写,说明未被占用
System.IO.FileStream stream = System.IO.File.OpenWrite( "文件路径" );
stream.Close();
}
catch
{
MessageBox.Show( "文件被占用!" );
return ;
}
|
3:WIN32 API调用(强烈推荐)
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
|
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;
}
}
}
}
|
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
原文链接:http://blog.csdn.net/u013816709/article/details/64922566
相关文章
猜你喜欢
- 个人服务器网站搭建:如何选择合适的服务器提供商? 2025-06-10
- ASP.NET自助建站系统中如何实现多语言支持? 2025-06-10
- 64M VPS建站:如何选择最适合的网站建设平台? 2025-06-10
- ASP.NET本地开发时常见的配置错误及解决方法? 2025-06-10
- ASP.NET自助建站系统的数据库备份与恢复操作指南 2025-06-10
TA的动态
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
您的支持,是我们最大的动力!
热门文章
-
2025-05-25 55
-
2025-06-04 40
-
2025-05-27 90
-
2025-05-25 97
-
2025-05-29 26
热门评论