简体   繁体   中英

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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