C# 该进程无法访问该文件,因为它正被另一个进程使用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2225087/
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-07 00:32:00  来源:igfitidea点击:

The process cannot access the file because it is being used by another process

c#asp.net

提问by Cragly

I am getting binary data from a SQL Server database field and am creating a document locally in a directory my application has permissions. However I am still getting the error specified in the title. I have tried numerous suggestions posted on the web including those suggested in previous posts on Stackoverflow. I have also used ProcessExplorer > Find Handle to locate the lock and it returns nothing as if the file is not locked.

我正在从 SQL Server 数据库字段获取二进制数据,并在我的应用程序具有权限的目录中本地创建文档。但是我仍然收到标题中指定的错误。我已经尝试了许多发布在网络上的建议,包括在 Stackoverflow 上之前的帖子中提出的建议。我还使用 ProcessExplorer > Find Handle 来定位锁,并且它不返回任何内容,就好像文件未锁定一样。

I am using the code below to save the file to the file system and I then try to copy this file to a new location later in the application process within another method. It is this copy method that takes the path of the newly created file that throws the exception.

我正在使用下面的代码将文件保存到文件系统,然后我尝试将此文件复制到稍后在​​应用程序进程中使用另一种方法的新位置。正是这个复制方法采用了引发异常的新创建文件的路径。

The file itself is created with its content and i can open it through Windows Explorer without any problems.

文件本身是用它的内容创建的,我可以通过 Windows 资源管理器打开它,没有任何问题。

Am I missing something completely obvious? Am I creating the file correctly from the database? Any help on solving or better diagnosing the problem would be much appreciated.

我错过了一些完全明显的东西吗?我是否从数据库正确创建了文件?任何有关解决或更好地诊断问题的帮助将不胜感激。

// Get file from DB
FileStream fs = new FileStream(
    "C:\myTempDirectory\myFile.doc", FileMode.OpenOrCreate, FileAccess.Write);
BinaryWriter br = new BinaryWriter(fs);
br.Write("BinaryDataFromDB");
fs.Flush();
fs.Close();
fs.Dispose();

// Copy file
File.Copy(sourceFileName, destinationFilename, true);

采纳答案by Jesper Palm

Try adding a call to GC.Collect()after you have disposed of your streams to force the garbage collector to clean up.

GC.Collect()处理完流后,尝试添加调用以强制垃圾收集器进行清理。

// Get file from DB 
using(FileStream fs = new FileStream("C:\myTempDirectory\myFile.doc", FileMode.OpenOrCreate, FileAccess.Write)) 
using(BinaryWriter br = new BinaryWriter(fs))
{
   br.Write("BinaryDataFromDB"); 
   fs.Flush(); 
}

//Force clean up
GC.Collect();

// Copy file 
File.Copy(sourceFileName, destinationFilename, true); 

回答by Bloodyaugust

Is it that Filestream and BinaryWriter cannot be used at the same time? For instance, a streamwriter and a streamreader cannot both be called on the same file. However, this doesn't make sense, as far as I know, it should not in this case. Perhaps try closing br as well?

是不是不能同时使用Filestream 和BinaryWriter?例如,不能在同一个文件上同时调用流写入器和流读取器。但是,这没有意义,据我所知,在这种情况下不应该。也许也尝试关闭 br?

回答by Steve Danner

Try disposing your BinaryWriter object before doing the copy.

在进行复制之前尝试处理您的 BinaryWriter 对象。

回答by bluecoder

Is there a background process such as antivirus or file-system indexing locking the file just long enough to cause problems with your application? Try pausing for 3 seconds to see if your problem disappears.

是否有后台进程(例如防病毒或文件系统索引)锁定文件的时间刚好足以导致应用程序出现问题?尝试暂停 3 秒钟,看看您的问题是否消失。

using System.Threading;

fs.Dispose();
Thread.Sleep(3000);
// Copy file

回答by Rubens Farias

What about using?

怎么样using

string source = @"C:\myTempDirectory\myFile.doc";
using(FileStream fs = new FileStream(
    source, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read))
{
    BinaryWriter br = new BinaryWriter(fs);
    br.Write("BinaryDataFromDB");
}

File.Copy(sourceFileName, destinationFilename, true);

EDIT: Try to inform a FileShare.Readpermission.

编辑:尝试通知FileShare.Read许可。

回答by NotMe

change your code as follows, the problem is that the the filestream isn't being garbage collected when you need it to:

如下更改您的代码,问题是文件流在您需要时没有被垃圾收集:

    // Get file from DB 
using (FileStream fs = new FileStream("C:\myTempDirectory\myFile.doc", FileMode.OpenOrCreate, FileAccess.Write)) 
{
    BinaryWriter br = new BinaryWriter(fs); 
    br.Write("BinaryDataFromDB"); 
    fs.Flush(); 
    fs.Close(); 
}

// Copy file 
File.Copy(sourceFileName, destinationFilename, true);

回答by murali

I came to understand that though the error debugger says that the error lies in this code.. But that isn't where the error is.. I faced a similar issue and I came with this solution.. consider all the posts above.. May be it may help some one..

我开始明白虽然错误调试器说错误出在这段代码中..但这不是错误所在..我遇到了类似的问题,我提出了这个解决方案..考虑上面的所有帖子..也许它可以帮助某人..



I used the Image to show it in a picturebox after retreiving from Database and saving it as "temp.bmp" using normal coding without using "using" keyword using this code at first:

在从数据库检索并使用普通编码将其保存为“temp.bmp”后,我使用图像将其显示在图片框中,而不使用“使用”关键字首先使用此代码:

PictureBox1.Image = Image.FromFile("temp.bmp");


and it raised and error and I really didn't got head and tail of the error.. and so I came up with this solution.

它引发和错误,我真的没有得到错误的头和尾..所以我想出了这个解决方案。



Instead of assigning it directly try this code:

而不是直接分配它试试这个代码:

Bitmap img;
using (Bitmap bmp = new Bitmap("temp.bmp"))
{
    img = new Bitmap(bmp);
}
pictureBox1.Image = img;

coming to the filestream part I just used normal code as follows:

来到文件流部分,我只是使用了普通代码,如下所示:

FileStream fs = new FileStream("filepath",FileMode.Create);

and it worked like a piece of cake

它就像小菜一碟



It really helped

它真的有帮助

回答by hakan

This was what I did:

这就是我所做的:

Stream stream = new MemoryStream();
var tempStream = new FileStream(pathToFile, FileMode.Open);
tempStream.CopyTo(stream);
tempStream.Close();

then use streamobject wherever you want.

然后stream在任何你想要的地方使用对象。

回答by Jon Boy

I seem to encounter this only after I have published an application. If you close the message box and try again to debug, nothing will happen. MS Help says to get all the way out of Visual Studio and restart it. Its easier to bring up Task manager and end the process. Its name will be the solution name followed by ".vshost" (e.g. project name: PLC.sln; process name: PLC.vshost.exe). The process will restart automatically. In Windows 7 one could usually see something happen when ending a process. But in 10 the Task Manager window rarely changes. I get this message when I try testing a program after changing code. Apparently the .exe is not closed when one stops debugging and the error occurs when VS tries to write a newly complied exe file. I sometimes have to end the process twice to keep the error message from coming back. (I have to encounter the error twice; ending the process twice and then rerunning doesn't help.) This is a bug in Visual Studio.

我似乎只有在发布应用程序后才会遇到这种情况。如果您关闭消息框并再次尝试调试,则不会发生任何事情。MS 帮助说完全退出 Visual Studio 并重新启动它。更容易调出任务管理器并结束进程。它的名称将是解决方案名称后跟“.vshost”(例如项目名称:PLC.sln;进程名称:PLC.vshost.exe)。该过程将自动重新启动。在 Windows 7 中,通常可以在结束进程时看到某些事情发生。但是在 10 中,任务管理器窗口很少发生变化。我在更改代码后尝试测试程序时收到此消息。显然,当停止调试时 .exe 没有关闭,并且当 VS 尝试编写新编译的 exe 文件时会发生错误。有时我必须两次结束该过程以防止错误消息再次出现。