C# 另一个进程使用的文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/626058/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 10:48:54  来源:igfitidea点击:

File used by another process

c#file-io

提问by NileshChauhan

Many a times we get an error, while trying to write file on Windows platform,

很多时候我们会在尝试在 Windows 平台上写入文件时遇到错误,

"The process cannot access the file 'XXX' because it is being used by another process."

“该进程无法访问文件‘XXX’,因为它正被另一个进程使用。”

How to check in C#, before writing to file that its not being used by another process?

如何在写入文件之前检查 C# 未被另一个进程使用?

采纳答案by Jon Skeet

You can't, basically - you have to attempt to open the file for writing, and if you get an exception you can't write to it :(

你不能,基本上 - 你必须尝试打开文件进行写入,如果出现异常,则无法写入:(

Even if you could do a separate check first, the result would be out of date before you could start writing - you could still end up with the exception later.

即使你可以先做一个单独的检查,结果在你开始写作之前就会过时——你以后仍然可能以异常告终。

It would be nice if the framework provided a TryOpenmethod, admittedly...

TryOpen诚然,如果框架提供了一种方法,那就太好了……

回答by Noldorin

The only option here is to catch the generated exception and handle it appropriately. See these other two SO threads for full discussions:

这里唯一的选择是捕获生成的异常并适当处理它。有关完整讨论,请参阅其他两个 SO 线程:

回答by David Bo?jak

Try putting the open command in a try-catch statement. If the file is being used IOException will be thrown.

尝试将 open 命令放在 try-catch 语句中。如果文件正在被使用,将抛出 IOException。

回答by Brian R. Bondy

You simply have to try the open with the sharing access you would like, and handle the error that is thrown.

您只需尝试使用您想要的共享访问权限打开,并处理引发的错误。

Note: Sometimes the file won't open simply because the file sharing rights you specified conflicts with the file sharing rights that someone already opened the file with.

注意:有时文件无法打开只是因为您指定的文件共享权限与某人已打开文件的文件共享权限冲突。

Please see my answer here for more information.

请在此处查看我的回答以获取更多信息

回答by Brian R. Bondy

Try to Rename the file if you are able to rename then it is confirm that no other process is accessing that file. Finally make sure that you have renamed the same file in the same folder.

如果可以重命名,请尝试重命名文件,然后确认没有其他进程正在访问该文件。最后确保您已重命名同一文件夹中的同一文件。

回答by Ionic? Biz?u

You must to closeyour file after using it on your code:

close在您的代码上使用它后,您必须对您的文件:

FileStream file = new FileStream(fileName, FileMode.Open, FileAccess.Read); //file is opened
//you use the file here 
file.Close(); //then you must to close the file