Hello
I'm trying to set a location/Path for my logFile but I cannot. It keeps creating it in the debug folder
StreamWriter logFile;
if (!File.Exists("logFile.txt"))
{
logFile = new StreamWriter(@"C:\logFile.txt");
}
else
{
logFile = File.AppendText("logFile.txt");
}
What is wrong in my code? and what if I need to create a specific folder (LogFolder) under C: Directory for example (if the folder does not exist) so that I can create the logFile inside of it.
Loading
Sunny SharmaPosted Sep 7, 2013, 6:01 AM
To answer your first question, Your code is working all fine. I assume you already have a file "logfile.txt" in debug folder and this is why your code is executing the else part of your code.
Please confirm if you don't have logfile.txt in debug folder.
For your second:
You can directly check if a Directory is there or not using Directory Class, like:
if(!Directory.Exist(@"C:\myDir"))
{
Directory.CreateDirectory(@"C:\myDir");
}
Hope it helps :)
Sunny SharmaPosted Sep 7, 2013, 8:33 AM
--------------------------------------------------------
StreamWriter logFile;
// I'm trying to check the directory here before I check the file, but doesn't work
string logFilePath="C:\myLogFilePath";
if(!Directory.Exist(logFilePath)
{
Directory.CreateDirectory(logFilePath);
}
if (!File.Exists(logFilePath+"\\logFile.txt"))
{
logFile = new StreamWriter(logFilePath+"\\logFile.txt");
}
else
{
logFile = File.AppendText("llogFilePath+"\\ogFile.txt");
}
//Write to the file:
logFile.WriteLine("Date Time: " + DateTime.Now);
logFile.WriteLine("File Name: " + fileName);
logFile.WriteLine("Number of Skipped Files: " + SkippedFiles);
logFile.WriteLine("Exception Name: " + sExceptionName);
logFile.WriteLine("End of the report");
//close stream
logFile.Close();
------------------------------------------------------------------------------
Hope it helps :)
Rano AHPosted Sep 7, 2013, 8:08 AM
Happy that you answered my question :-) , good to hear that my code is fine.
Yes, there was a logFile in the debug folder and when I deleted it the logFile created in the directory I assigned :-)
But, for the second part, not sure how to do this (check the folder if exist and if not create it and then check the file if exist, if not create a file, or else append to file.
I'm trying to do this, but getting errors :-(
Below is my function that creates the logFile
{
StreamWriter logFile;
// I'm trying to check the directory here before I check the file, but doesn't work
if (!File.Exists("logFile.txt"))
{
logFile = new StreamWriter(@"C:\LogFolder\logFile.txt");
}
else
{
logFile = File.AppendText("logFile.txt");
}
//Write to the file:
logFile.WriteLine("Date Time: " + DateTime.Now);
logFile.WriteLine("File Name: " + fileName);
logFile.WriteLine("Number of Skipped Files: " + SkippedFiles);
logFile.WriteLine("Exception Name: " + sExceptionName);
logFile.WriteLine("End of the report");
//close stream
logFile.Close();