C# example code doesn't release file properly
A unified display of relevant technical and tag data for A/V files
Brought to you by:
guillaumeroques,
zenitram
I'm using MediaInfo with C#. After calling this method, it doesn't release the file properly. I cannot delete or rename a file after reading it with this.
How can I properly release the file?
private MediaInfo ReadMediaFile(string fileName) { //Initilaizing MediaInfo MediaInfo MI = new MediaInfo(); //From: preparing an example file for reading FileStream From = new FileStream(fileName, FileMode.Open, FileAccess.Read); //From: preparing a memory buffer for reading byte[] From_Buffer = new byte[64 * 1024]; int From_Buffer_Size; //The size of the read file buffer //Preparing to fill MediaInfo with a buffer MI.Open_Buffer_Init(From.Length, 0); //The parsing loop do { //Reading data somewhere, do what you want for this. From_Buffer_Size = From.Read(From_Buffer, 0, 64 * 1024); //Sending the buffer to MediaInfo System.Runtime.InteropServices.GCHandle GC = System.Runtime.InteropServices.GCHandle.Alloc(From_Buffer, System.Runtime.InteropServices.GCHandleType.Pinned); IntPtr From_Buffer_IntPtr = GC.AddrOfPinnedObject(); Status Result = (Status)MI.Open_Buffer_Continue(From_Buffer_IntPtr, (IntPtr)From_Buffer_Size); GC.Free(); if ((Result & Status.Finalized) == Status.Finalized) break; //Testing if MediaInfo request to go elsewhere if (MI.Open_Buffer_Continue_GoTo_Get() != -1) { Int64 Position = From.Seek(MI.Open_Buffer_Continue_GoTo_Get(), SeekOrigin.Begin); //Position the file MI.Open_Buffer_Init(From.Length, Position); //Informing MediaInfo we have seek } } while (From_Buffer_Size > 0); //Finalizing MI.Open_Buffer_Finalize(); //This is the end of the stream, MediaInfo must finnish some work return MI; }
The code you are using is an example of how to use MediaInfo "by buffer" interface, so MediaInfo handles no file properties. It is impossible for MediaInfo to block something about the file because MediaInfo is not aware of a file (it is aware of a memory buffer, that's all).
This is only an example, adapt it for your needs.
I don't know a lot about C#, maybe the Close method is not called automaticly, and called only when the garbage collector does its job?
Try to add From.Close() before returning the object.
Oh, the bug is in C#? Yes, indeed, the problem is in these few lines.
"From" is the file stream and it isn't being closed. Adding this line at the end solves the problem.
From.Close();