简体   繁体   English

如何使用 Directory.EnumerateFiles 关闭文件以循环遍历文件 C#

[英]How to close a file using Directory.EnumerateFiles to loop through files C#

Ive searched high and low and cant find anything specific, maybe because my knowledge is limited.我搜索了高低,找不到任何具体的东西,可能是因为我的知识有限。

I am looping through files and doing "stuff" with it :我正在遍历文件并用它做“东西”:

foreach (var file in Directory.EnumerateFiles(scannedFilesLocation, "*.tif"))
{               
    fileName = Path.GetFileName(file.ToString());

    var tifImage = Image.FromFile(file.ToString());
    // var imageContent = ImageHelper.ImageToByteArray(tifImage);
    var tiffArray = File.ReadAllBytes(file);
    string contentType = "";

    new FileExtensionContentTypeProvider().TryGetContentType(fileName, out contentType);

    var newScannedDocument = new AddDocumentToFileStore();

    newScannedDocument.DocumentName = fileName;
    newScannedDocument.ContentType = contentType;
    newScannedDocument.Content = tiffArray;
    newScannedDocument.Meta.Add("FileName", fileName);

    newScannedDocumentList.Add(newScannedDocument);
}

At the end of the loop, I want to move or delete the file, but when I use File.Delete(...) I get an error stating that the file is in use - Which I completely understand, but how do I close this specific file to perform this Delete ?在循环结束时,我想移动或删除文件,但是当我使用File.Delete(...)我收到一条错误消息,指出该文件正在使用中 - 我完全理解,但我该如何关闭这个特定的文件来执行这个Delete

Thanks for any help!谢谢你的帮助!

Edit: It seems like this post changed from the way I first read it a minute ago.编辑:这篇文章似乎与我一分钟前第一次阅读的方式有所不同。

This might work:这可能有效:

// destroy the reference
tifImage.Dispose();

Or或者

using (Image image = Image.FromFile(fileName))
{
   // do your processing
}

I think that works, from very used memory above my neck.我认为这是有效的,从我脖子上非常用过的记忆来看。

Another thing you might could try is make a copy of the file and do your 'stuff'.您可以尝试的另一件事是制作文件的副本并做您的“东西”。

System.IO.File.Copy(source, target); // (I think that is right, I don't have VS open at the moment).

This way your original never got a handle opened, and if your copy is in a temp location, and for whatever reason you are unable to delete the copy during the processing of your file, delete it periodically.这样,您的原件永远不会打开句柄,如果您的副本位于临时位置,并且无论出于何种原因您无法在处理文件期间删除副本,请定期将其删除。

Maybe that helps, or you can do your deletes later in another process.也许这会有所帮助,或者您可以稍后在另一个过程中进行删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM