在C#中删除文件时出现文件访问错误 [英] Getting file access error while deleting a file in C#

查看:117
本文介绍了在C#中删除文件时出现文件访问错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我正在使用AsParallel迭代目录中的列表文件将它们复制到其他位置,之后当我尝试删除它们时,我收到文件访问错误说它正在被另一个进程使用。



有人可以告诉它导致问题的原因。


我尝试过:



Hi,
I am using AsParallel to iterate through a list files in a directory to copy them to some other location, after which when I try to delete them I am getting file access error saying it is being using by another process.

Can someone tell where it is causing the issue.

What I have tried:

command.OutputDirectory
                    .GetFilesWhere(source => source.Extension.In(command.OutputExtensions))
                    .AsParallel()
                    .ForEach(source =>
                    {
                        Logger.LogInfo(@"Copying [{0}] to [{1}]...".FormatWith(source.FullName, OutputDirectory));
                        source.CopyTo(OutputDirectory.PathCombine(source.Name), true);                        
                        try
                        {
                             source.Delete();
                        }
                        catch (Exception e)
                        {
                            Logger.LogError("Exception while deleting the output file: " + e.Message);
                        }
                    }
                    );

推荐答案

错误消息告诉您问题所在:

The error message tells you what the problem is:
I am getting file access error saying it is being using by another process



该文件正在使用中:是开放的,因此被锁定。



某处 - 可能是你代码中的其他地方 - 你已经打开了文件(可能是为了写访问,但可以读取)和没有关闭你打开的流。在该流关闭之前,该文件已被锁定,无法重新打开以进行写入或删除。



因此,请使用细齿梳理您的代码:查看您引用该文件的所有位置,并按照它直到关闭流。如果不关闭它,则无法将其删除 - 因此,当您完成文件后,请关闭并处置您用来访问它的对象。


The file is in use: it is open and as a result locked.

Somewhere - probably elsewhere in your code - you have opened the file (probably for write access, but it could be read) and not closed the stream that you opened. Until that stream is closed, the file is locked and cannot be reopened for writing or deleted.

So go through your code with a fine tooth comb: look at everywhere you reference that file, and follow it until you close the stream. If you don't close it, you can't delete it - so when you are finished with the file, close and dispose the objects you used to access it.


这篇关于在C#中删除文件时出现文件访问错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆