I have a very strange issue with a windows service and console app I developed. The windows service is written in c# .net core. What it does is it takes a zip file of a pre built .net core console app and unzips it to a location then calls Process.Start to run it.
There are multiple threads that call into the service and that service will then unzip the file if not already unzipped and then call Process.Start for each request thread. The unzipping is thread safe.
What happens is that sometimes when the console app starts it crashes with a BadImageFormatException on a random dll. Any subsequent calls to process start will crash with the same error on the same dll.
If I stop the service and run the console app manually it crashes with the same BadImageFormatException error.
Now this is were it gets strange. If I copy the folder where the console app is to another place on the same drive on the same machine and run it - it works as normal.
If I copy the dll that had the BadImageFormatException from the original folder to a temp folder, delete the original dll, then copy back the backup to the original folder and re run the app - it works as normal.
I've been struggling to come up with a reason behind this. What could cause a BadImageFormatException for a .net core console app if the same app can be run on the same machine just by coping it to another folder?
I've seen this on several windows server machines from 2012 r2 to 2016.
Update
So from more testing it seems that whenever I get the BadImageFormatException running the console app I can get it to work again by clearing the windows file cache using RAMMap from sysinternals.
So the question now is why are dlls either being modified or corrupted in the file cache? I am launching multiple processes at once (can be up to 40 at times) but that shouldn't cause dll to be modified and throw a BadImageFormatException . Is it something in the way .NetCore loads? Or is it the way I unzip the folder? I'm using System.IO.Compression zip libraries eg:
ZipFile.ExtractToDirectory(zipFile, outFolder);