我正在尝试确定文件当前是打开还是使用C#写入.我已经看到类似的SO问题,所有问题都与我的代码类似,它在文件上尝试File.Open.但是当我使用下面的代码运行程序时,我也手动打开文件,我得到"文件当前未锁定"的意外结果.有什么想法/建议/我遗失的任何东西?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading;
namespace TestIfFileAccessed
{
class Program
{
static void Main(string[] args)
{
string path = @"C:\TEMP\testFile.txt";
FileInfo filepath = new FileInfo(path);
if (IsFileLocked(filepath)) {
Console.WriteLine("File is currently locked");
Console.ReadLine();
}
else
{
Console.WriteLine("File is currently NOT locked");
Console.ReadLine();
}
}
public static bool IsFileLocked(FileInfo file)
{
FileStream stream = null;
try
{
stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
}
catch (IOException)
{
//the file is unavailable because it is:
//still being written to
//or being processed by another thread
//or does not exist (has already been processed)
return true;
}
finally
{
if (stream != null)
stream.Close();
}
//file is not locked
return false;
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6007 次 |
| 最近记录: |