You're going about the problem the wrong way; rather than try to invent your own method for creating new files, simply use an existing library like NLog or log4net to do it for you which has already taken care of all the problems with concurrent access and other considerations.
I don't know log4net as well, but for NLog, you can do it like this (log4net should be similar):
1) Download NLog, add it as a reference in your project
2) Configure NLog by creating NLog.config and setting it to be copied to the output folder on build. Here's a simple config file that will simply log to the current directory and archive if the file gets too big:
<?xml version="1.0" encoding="utf-8"?> <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" autoReload="true"> <targets> <target name="targetFile" xsi:type="File" fileName="log.txt" archiveAboveSize="1000000" archiveNumbering="Sequence" /> </targets> <rules> <logger name="*" minlevel="Trace" writeTo="targetFile" /> </rules> </nlog>
3) Add this to your class properties (and anywhere else you want to log):
private readonly Logger logger = LogManager.GetCurrentClassLogger();
Then, any time you want to log, simply do:
logger.Info(responseFromServer);
Edit:
In my testing, the concurrent writes algorithm used by NLog may discard messages if too many messages come at once and it has to fight for access to the file (however, it will not throw an exception). You can make each process log to its own file if you want to make sure to never lose messages by inserting ${processid} in the config file, for the log location, like so:
<target name="targetFile" xsi:type="File" fileName="log_${processid}.txt" archiveAboveSize="1000000" archiveNumbering="Sequence" />