Reputation: 1738
I am getting an error when I run this newFile method:
class logFile
{
public static string logpath = @"D:\Program Files\CustomApps\DataFeed\";
public static void log(string log)
{
string timestamp = DateTime.Now.ToString("yyyy_MM_ddTHH_mm_ss");
Console.WriteLine(timestamp + log);
File.AppendAllText(logpath + @"log_file_current.txt", timestamp + log + Environment.NewLine);
}
public static void newFile()
{
if (File.Exists(logpath + @"log_file_current.txt") == true)
{
File.Move(logpath + @"log_file_current.txt"
, logpath + @"log_files\log_file_ORPHANED_" + DateTime.Now.ToString("yyyy_MM_ddTHH_mm_ss") + ".txt");
}
try
{
File.Create(logpath + @"log_file_current.txt");
logFile.log("logFile created.");
}
catch(System.NotSupportedException ex)
{
Console.WriteLine(ex.Message);
}
}
}
I get the following error:
If I comment the body of the "newFile" code out then it runs without error, but then I would need to manually archive. If I comment out the File.Move
part it all runs fine so this is the culprit.
How can I release the file so that it can be moved?
Upvotes: 0
Views: 1870
Reputation: 187
You need to use File.Close after using File.Create, this is why you are getting an error saying the file is used by another process. Try adding this line to your code :
try
{
File.Create(logpath + @"log_file_current.txt").Close(); // Notice the .Close() here
logFile.log("logFile created.");
}
Source : Closing a file after File.Create
Upvotes: 3
Reputation: 902
Try this one
public static void log(string log)
{
string timestamp = DateTime.Now.ToString("yyyy_MM_ddTHH_mm_ss") + ": ";
Console.WriteLine(timestamp + log);
using (StreamWriter sw = File.AppendText(logpath + @"log_file_current.txt"))
{
sw.WriteLine(timestamp + log);
}
}
Upvotes: 0