Tuesday, 20 August 2013

File.Create Throwing IOException

File.Create Throwing IOException

I have a program that employs a simple logging process. The idea is that
every day a new file gets created that corresponds with the date unless
the file already exists, in which case it's just appended to. The problem
is, File.Create is throwing an error every time it runs. I found a
solution to the problem that says File.Create is opening a FileStream and
you just need to call it with a .close(); but that solution didn't work
for me, I'm still getting the IO exception saying that the file is in use
by another process, which is impossible since it doesn't exist until
File.Create creates it, and nothing else uses these files.
Here's the code:
public static void logResults(System.Reflection.MethodBase method, Results
result, string message)
{
string date = DateTime.Now.ToString();
int index = date.IndexOf(" ");
string subString = date.Substring(0, index);
string nwDate = Regex.Replace(subString, "/", "");
logFileName = "WebsiteRegressionProduction_TestCycle." + nwDate;
string currentLogFile = logFileLocation + @"\" + logFileName;
StringBuilder sb = new StringBuilder();
if (!File.Exists(currentLogFile))
{
File.Create(currentLogFile).Close();
sb.Append("DATE-TIME\tACTION\tTEST CLASS\tTEST NAME\tTEST
STATUS\tERROR MESSAGES");
sb.Append("\n");
}
else
{
string previousLogs = File.ReadAllText(currentLogFile);
sb.Append(previousLogs);
}
sb.Append(DateTime.Now.ToString());
sb.Append(" : ");
sb.Append("Text Executed: ");
sb.Append(method.ReflectedType.Name + " : ");
sb.Append(method + " : ");
sb.Append(result.ToString());
sb.Append(" : ");
sb.Append(message);
sb.Append("\n");
sb.Append("\n");
File.WriteAllText(currentLogFile, sb.ToString());

No comments:

Post a Comment