Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Debugging file handle issues in c#/.NET

I have a program that in turn accesses a DLL. It uses files in various ways, creating them, copying them and establishing them as attachments to an emailMessage object. I have a 'file in use' error, preventing overwrite of a file.

Is there any tool or technique for easing the process - eg some kind of warning of the creation / removal of handles containing a particular string? I've looked at process explorer, process monitor (the successor to filemon) etc but no luck.

I can keep hunting, but thought there might be a better approach than continuing my informal investigations through the code.

EDIT

Thanks for the comments. Regarding the questions, the structure is a bit complex. I have my 'client' app which references an 'Engine' dll (in C# also). Both are my own. The client creates instances of 'attachments' each of which contain a file reference to various files. The constructor of that grabs the file referred to, and puts a copy in a temporary folder. Later, a set of 'actions' builds the email - it adds each attachment as a 'real' attachment to an EmailMessage object. At various times I dispose of the objects and set their references to null, but if I do it too early then I end up with null reference exceptions. If I do it too late, the damn things are in use! I'm sure I can hunt down this specific bug in due course, but it prompted me to wonder if there is a useful standard method used by those in the know. :)

like image 540
Glinkot Avatar asked Jan 19 '12 22:01

Glinkot


2 Answers

Procmon will tell you who (i.e. which process) is opening the file, and the (unmanaged) stack of the place that opened it.

The usual cause of this problem in C#/.NET is people opening file streams and not disposing when they've finished with them. This means the file stays open until (at least) the next garbage collection, which can be ages away.

like image 87
Will Dean Avatar answered Sep 20 '22 19:09

Will Dean


It sounds like you're looking for a tool to let you know what is locking the file while debugging. If so, you can use Unlocker to determine the process locking the file.

like image 30
Frazell Thomas Avatar answered Sep 21 '22 19:09

Frazell Thomas