【发布时间】:2015-08-07 03:47:19
【问题描述】:
我正在尝试确定文件当前是否打开或正在使用 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;
}
}
}
【问题讨论】:
-
至少在那个
file.Open()上加上一个using(...)声明。 -
手动打开文件时确定文件被锁定了吗?
-
@whoisj 你认为
stream.Dispose()有什么stream.Close()还没有做到? -
也许您在将文件读入内存的程序中打开文件。如果您使用
FileInfo.Open在另一个程序中打开它并且不关闭它,也许这会起作用。试一试:) -
很难猜测“也手动打开文件”可能意味着什么。好吧,不是你想的那样。许多读取 .txt 文件的程序只是读取其内容并再次关闭文件。像记事本或 VS。