Link to home
Start Free TrialLog in
Avatar of oneDayAtaTime
oneDayAtaTimeFlag for United States of America

asked on

Windows File Locks Interfering with C# StreamWriter

I have a Windows application written in C# that utilizes StreamWriter to create an HTML file. It grabs the HTML from a table and creates a file from it. My issue is that on some occasions, the application user has the need to create the file within minutes of initially creating the file. Sometimes when this happens, the file is "locked" by Windows and won't allow StreamWriter to write to it. Most times it seems to release the lock right away, but not every time.
   It seems this is more a Windows problem than a StreamWriter problem. If I could find a way to manually unlock the file (through C#), if it's locked, that would prevent the hang-up. But I'm not sure that's possible.
   I've attached the code that creates the file. I've enclosed my StreamWriter call within a "using" block, because that is supposed to dispose of all unmanaged resources. I don't know what else I can do from my end, to ensure the file doesn't remain locked.
   Any ideas on how to keep my code from hanging because of a locked file? It's weird because if I have the file open, it still writes to it (so is apparently not locked). I don't know why the file is locked sometimes after creation.
                                          Thanks!
                                                  Joyce
StreamWriter.doc
ASKER CERTIFIED SOLUTION
Avatar of wdosanjos
wdosanjos
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of oneDayAtaTime

ASKER

YES, thank you!!!! I now think I was looking in the wrong place. Once I create the file, I have a Windows Service that picks it up and sends it via email. It is also in C#, and I think THAT is where the file-locking is happening. I've added a "email.Attachments.Dispose();" line that will perform clean-up after the email is sent. Hopefully this will correct my problem. Thank you for helping me to see the problem in a different light! Also thanks for verifying that the "using" block performs clean-up.
                              Joyce