I built a small class named "ErrorLog" through which the application creates a text file for each session and writes detailed error messages in it whenever the case. I am aware that this might not be the best approach for a logging class but I find this
more comfortable and easier to use, especially for debugging reasons. However, if anyone knows/prefers another approach I'd gladly consider it.
So I added a new Class Library Project to my current solution and build my class' functionality as follows:
My class checks for and creates if needed a directory named 'ErrorLog' in the application startup path, inside which it will create another directory named 'DD-MM-YYYY' (ShortDateString). In this last directory a text file will be created for each application
session and its name will be 'HH-MM-SS' (Hours-Minutes-Seconds).
I create the file using the File.Create() method, and for the writing I use a StreamWriter object.
This works smoothly in my solution, but if I try to use the same class, either as .dll file or as new class library project, I get an exception which states that The process cannot access the file <full_fileName> because it is being used by another
process, and that 'another' process is my application (or that's what Unlocker is telling me).
File.Create not only creates the file, it also opens the file and returns a FileStream. Since you ignore the result the stream won't be closed until the GC collects it, that can take a while.
Ideally you should create a StreamWriter on the stream returned by File.Create and use the writer in WriteLog. Note that the writer should probably be stored in a static, otherwise each ErrorLog instance will try to create/open the same file.
Proposed as answer byRagu.RMonday, November 28, 2011 12:22 PM
Marked as answer bydan001Monday, November 28, 2011 12:29 PM