Daw*_*wsy 809 .net c# file-io file file-locking
我正在用C#编写一个需要重复访问1个图像文件的程序.大部分时间它都可以工作,但如果我的计算机运行速度很快,它会在将文件保存回文件系统之前尝试访问该文件并抛出错误:"另一个进程正在使用的文件".
我想找到解决这个问题的方法,但是我所有的谷歌搜索都只是通过使用异常处理来创建检查.这违背了我的宗教信仰,所以我想知道是否有人有更好的方法呢?
Spe*_*nce 541
您可能会遇到线程争用情况,其中有文档示例将此用作安全漏洞.如果您检查该文件是否可用,但是然后尝试使用它,那么您可能会抛出这一点,恶意用户可以使用它来强制和利用您的代码.
你最好的选择是尝试catch/finally,它试图获取文件句柄.
try
{
using (Stream stream = new FileStream("MyFilename.txt", FileMode.Open))
{
// File/Stream manipulating code here
}
} catch {
//check here why it failed and ask user to retry if the file is in use.
}
Run Code Online (Sandbox Code Playgroud)
Chr*_*isW 524
更新了此解决方案的注意事项:FileAccess.ReadWrite对于只读文件,检查将失败,因此已修改解决方案以进行检查FileAccess.Read.虽然此解决方案有效,因为FileAccess.Read如果文件上有写入或读取锁定,尝试检查将失败,但是,如果文件上没有写入或读取锁定,则此解决方案将无效,即它已打开(用于读取或写入)使用FileShare.Read或FileShare.Write访问.
原文: 过去几年我使用过这段代码,我没有遇到任何问题.
了解您对使用异常的犹豫,但您无法一直避免它们:
protected virtual bool IsFileLocked(FileInfo file)
{
try
{
using(FileStream stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.None))
{
stream.Close();
}
}
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;
}
//file is not locked
return false;
}
Run Code Online (Sandbox Code Playgroud)
Jer*_*son 88
用它来检查文件是否被锁定:
using System.IO;
using System.Runtime.InteropServices;
internal static class Helper
{
const int ERROR_SHARING_VIOLATION = 32;
const int ERROR_LOCK_VIOLATION = 33;
private static bool IsFileLocked(Exception exception)
{
int errorCode = Marshal.GetHRForException(exception) & ((1 << 16) - 1);
return errorCode == ERROR_SHARING_VIOLATION || errorCode == ERROR_LOCK_VIOLATION;
}
internal static bool CanReadFile(string filePath)
{
//Try-Catch so we dont crash the program and can check the exception
try {
//The "using" is important because FileStream implements IDisposable and
//"using" will avoid a heap exhaustion situation when too many handles
//are left undisposed.
using (FileStream fileStream = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None)) {
if (fileStream != null) fileStream.Close(); //This line is me being overly cautious, fileStream will never be null unless an exception occurs... and I know the "using" does it but its helpful to be explicit - especially when we encounter errors - at least for me anyway!
}
}
catch (IOException ex) {
//THE FUNKY MAGIC - TO SEE IF THIS FILE REALLY IS LOCKED!!!
if (IsFileLocked(ex)) {
// do something, eg File.Copy or present the user with a MsgBox - I do not recommend Killing the process that is locking the file
return false;
}
}
finally
{ }
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
出于性能原因,我建议您在同一操作中读取文件内容.这里有些例子:
public static byte[] ReadFileBytes(string filePath)
{
byte[] buffer = null;
try
{
using (FileStream fileStream = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
int length = (int)fileStream.Length; // get file length
buffer = new byte[length]; // create buffer
int count; // actual number of bytes read
int sum = 0; // total number of bytes read
// read until Read method returns 0 (end of the stream has been reached)
while ((count = fileStream.Read(buffer, sum, length - sum)) > 0)
sum += count; // sum is a buffer offset for next reading
fileStream.Close(); //This is not needed, just me being paranoid and explicitly releasing resources ASAP
}
}
catch (IOException ex)
{
//THE FUNKY MAGIC - TO SEE IF THIS FILE REALLY IS LOCKED!!!
if (IsFileLocked(ex))
{
// do something?
}
}
catch (Exception ex)
{
}
finally
{
}
return buffer;
}
public static string ReadFileTextWithEncoding(string filePath)
{
string fileContents = string.Empty;
byte[] buffer;
try
{
using (FileStream fileStream = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
int length = (int)fileStream.Length; // get file length
buffer = new byte[length]; // create buffer
int count; // actual number of bytes read
int sum = 0; // total number of bytes read
// read until Read method returns 0 (end of the stream has been reached)
while ((count = fileStream.Read(buffer, sum, length - sum)) > 0)
{
sum += count; // sum is a buffer offset for next reading
}
fileStream.Close(); //Again - this is not needed, just me being paranoid and explicitly releasing resources ASAP
//Depending on the encoding you wish to use - I'll leave that up to you
fileContents = System.Text.Encoding.Default.GetString(buffer);
}
}
catch (IOException ex)
{
//THE FUNKY MAGIC - TO SEE IF THIS FILE REALLY IS LOCKED!!!
if (IsFileLocked(ex))
{
// do something?
}
}
catch (Exception ex)
{
}
finally
{ }
return fileContents;
}
public static string ReadFileTextNoEncoding(string filePath)
{
string fileContents = string.Empty;
byte[] buffer;
try
{
using (FileStream fileStream = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
int length = (int)fileStream.Length; // get file length
buffer = new byte[length]; // create buffer
int count; // actual number of bytes read
int sum = 0; // total number of bytes read
// read until Read method returns 0 (end of the stream has been reached)
while ((count = fileStream.Read(buffer, sum, length - sum)) > 0)
{
sum += count; // sum is a buffer offset for next reading
}
fileStream.Close(); //Again - this is not needed, just me being paranoid and explicitly releasing resources ASAP
char[] chars = new char[buffer.Length / sizeof(char) + 1];
System.Buffer.BlockCopy(buffer, 0, chars, 0, buffer.Length);
fileContents = new string(chars);
}
}
catch (IOException ex)
{
//THE FUNKY MAGIC - TO SEE IF THIS FILE REALLY IS LOCKED!!!
if (IsFileLocked(ex))
{
// do something?
}
}
catch (Exception ex)
{
}
finally
{
}
return fileContents;
}
Run Code Online (Sandbox Code Playgroud)
亲自尝试一下:
byte[] output1 = Helper.ReadFileBytes(@"c:\temp\test.txt");
string output2 = Helper.ReadFileTextWithEncoding(@"c:\temp\test.txt");
string output3 = Helper.ReadFileTextNoEncoding(@"c:\temp\test.txt");
Run Code Online (Sandbox Code Playgroud)
asd*_*101 15
我最近遇到了这个问题并发现了这个: https: //learn.microsoft.com/en-us/dotnet/standard/io/handling-io-errors。
在这里,Microsoft 描述了以下方法来检查是否IOException由于锁定文件而导致:
catch (IOException e) when ((e.HResult & 0x0000FFFF) == 32 ) {
Console.WriteLine("There is a sharing violation.");
}
Run Code Online (Sandbox Code Playgroud)
也许您可以使用FileSystemWatcher并监视Changed事件.
我自己没有用过,但它可能值得一试.如果filesystemwatcher在这种情况下有点重,我会选择try/catch/sleep循环.
只需按预期使用例外.接受文件正在使用中并重复尝试,直到您的操作完成.这也是最有效的,因为在行动之前不会浪费任何检查状态的周期.
例如,使用下面的功能
TimeoutFileAction(() => { System.IO.File.etc...; return null; } );
Run Code Online (Sandbox Code Playgroud)
可重复使用的方法,在2秒后超时
private T TimeoutFileAction<T>(Func<T> func)
{
var started = DateTime.UtcNow;
while ((DateTime.UtcNow - started).TotalMilliseconds < 2000)
{
try
{
return func();
}
catch (System.IO.IOException exception)
{
//ignore, or log somewhere if you want to
}
}
return default(T);
}
Run Code Online (Sandbox Code Playgroud)
上面接受的答案会遇到一个问题,如果文件已打开以使用 FileShare.Read 模式进行写入,或者文件具有只读属性,则代码将无法工作。这个修改后的解决方案最可靠,需要记住两件事(对于接受的解决方案也是如此):
记住上述内容,这将检查文件是否被锁定以进行写入或锁定以防止读取:
public static bool FileLocked(string FileName)
{
FileStream fs = null;
try
{
// NOTE: This doesn't handle situations where file is opened for writing by another process but put into write shared mode, it will not throw an exception and won't show it as write locked
fs = File.Open(FileName, FileMode.Open, FileAccess.ReadWrite, FileShare.None); // If we can't open file for reading and writing then it's locked by another process for writing
}
catch (UnauthorizedAccessException) // https://msdn.microsoft.com/en-us/library/y973b725(v=vs.110).aspx
{
// This is because the file is Read-Only and we tried to open in ReadWrite mode, now try to open in Read only mode
try
{
fs = File.Open(FileName, FileMode.Open, FileAccess.Read, FileShare.None);
}
catch (Exception)
{
return true; // This file has been locked, we can't even open it to read
}
}
catch (Exception)
{
return true; // This file has been locked
}
finally
{
if (fs != null)
fs.Close();
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
static bool FileInUse(string path)
{
try
{
using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate))
{
fs.CanWrite
}
return false;
}
catch (IOException ex)
{
return true;
}
}
string filePath = "C:\\Documents And Settings\\yourfilename";
bool isFileInUse;
isFileInUse = FileInUse(filePath);
// Then you can do some checking
if (isFileInUse)
Console.WriteLine("File is in use");
else
Console.WriteLine("File is not in use");
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助!
小智 5
您可以返回一个任务,该任务将在流可用时立即为您提供。这是一个简化的解决方案,但这是一个很好的起点。这是线程安全的。
private async Task<Stream> GetStreamAsync()
{
try
{
return new FileStream("sample.mp3", FileMode.Open, FileAccess.Write);
}
catch (IOException)
{
await Task.Delay(TimeSpan.FromSeconds(1));
return await GetStreamAsync();
}
}
Run Code Online (Sandbox Code Playgroud)
您可以照常使用此流:
using (var stream = await FileStreamGetter.GetStreamAsync())
{
Console.WriteLine(stream.Length);
}
Run Code Online (Sandbox Code Playgroud)
据我所知,这里有一些代码与接受的答案具有相同的功能,但代码较少:
public static bool IsFileLocked(string file)
{
try
{
using (var stream = File.OpenRead(file))
return false;
}
catch (IOException)
{
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
但我认为通过以下方式进行更稳健:
public static void TryToDoWithFileStream(string file, Action<FileStream> action,
int count, int msecTimeOut)
{
FileStream stream = null;
for (var i = 0; i < count; ++i)
{
try
{
stream = File.OpenRead(file);
break;
}
catch (IOException)
{
Thread.Sleep(msecTimeOut);
}
}
action(stream);
}
Run Code Online (Sandbox Code Playgroud)
除了工作 3-liners 和仅供参考:如果你想要完整的信息 - 微软开发中心有一个小项目:
https://code.msdn.microsoft.com/windowsapps/How-to-know-the-process-704839f4
现在发现:https : //github.com/TacticalHorse/LockFinder/blob/master/LockFinder.cs
从简介:
在 .NET Framework 4.0 中开发的 C# 示例代码将有助于找出锁定文件的进程。 rstrtmgr.dll中包含的RmStartSession函数已用于创建重启管理器会话,并根据返回结果创建 Win32Exception 对象的新实例。通过RmRegisterResources函数将资源注册到 Restart Manager 会话后 ,调用RmGetList函数通过枚举RM_PROCESS_INFO数组来检查哪些应用程序正在使用特定文件。
它通过连接到“重新启动管理器会话”来工作。
重新启动管理器使用在会话中注册的资源列表来确定必须关闭和重新启动哪些应用程序和服务。 资源可以通过文件名、服务短名称或描述正在运行的应用程序的RM_UNIQUE_PROCESS 结构来标识。
对于您的特定需求,它可能有点过度设计……但如果这是您想要的,请继续使用 vs-project。
| 归档时间: |
|
| 查看次数: |
494556 次 |
| 最近记录: |