.net - How can I load an Image from a file without keeping the file locked? -


i wish display image in picturebox, loading image file. file gets overwritten periodically though, can't keep file locked. started doing this:

picturebox.image = image.fromfile( filename );

however, keeps file locked. tried read through stream:

using (system.io.filestream fs = new system.io.filestream(filename, system.io.filemode.open, system.io.fileaccess.read)) {     picturebox.image = image.fromstream(fs); }  

this doesn't lock file, does cause exception thrown later on; msdn indicates stream must kept open lifetime of image. (the exception includes message "a closed file may not read" or similar.)

how can load image file, have no further references file?

sorry answer own question, thought useful keep myself.

the trick copy data file stream memory stream before loading image. file stream may closed safely.

using (system.io.filestream fs = new system.io.filestream(filename, system.io.filemode.open, system.io.fileaccess.read)) {     system.io.memorystream ms = new system.io.memorystream();     fs.copyto(ms);     ms.seek(0, system.io.seekorigin.begin);     picturebox.image = image.fromstream(ms); }  

Comments

Popular posts from this blog

c# - how to write client side events functions for the combobox items -

exception - Python, pyPdf OCR error: pyPdf.utils.PdfReadError: EOF marker not found -