[英]How to close a file using Directory.EnumerateFiles to loop through files C#
我搜索了高低,找不到任何具體的東西,可能是因為我的知識有限。
我正在遍歷文件並用它做“東西”:
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);
}
在循環結束時,我想移動或刪除文件,但是當我使用File.Delete(...)
我收到一條錯誤消息,指出該文件正在使用中 - 我完全理解,但我該如何關閉這個特定的文件來執行這個Delete
?
謝謝你的幫助!
編輯:這篇文章似乎與我一分鍾前第一次閱讀的方式有所不同。
這可能有效:
// destroy the reference
tifImage.Dispose();
或者
using (Image image = Image.FromFile(fileName))
{
// do your processing
}
我認為這是有效的,從我脖子上非常用過的記憶來看。
您可以嘗試的另一件事是制作文件的副本並做您的“東西”。
System.IO.File.Copy(source, target); // (I think that is right, I don't have VS open at the moment).
這樣,您的原件永遠不會打開句柄,如果您的副本位於臨時位置,並且無論出於何種原因您無法在處理文件期間刪除副本,請定期將其刪除。
也許這會有所幫助,或者您可以稍后在另一個過程中進行刪除。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.