theHeXaGoNdev
theHeXaGoNdev

Reputation: 19

Simple C# log file

I have a program, and I want it to log stuff into a .txt file with this technique:

if (Directory.Exists(@"C:\Log"))
        {
            string[] start = { DateTime.Now + ": Program Started\n" };
            File.WriteAllLines(@"C:\Log\Log.txt", start);
            Console.Clear();
        }
        else
        {
            Directory.CreateDirectory(@"C:\Log");
            string[] start = { DateTime.Now + ": Program Started\n" };
            File.WriteAllLines(@"C:\Log\Log.txt", start);
            Console.Clear();
        }

With this technique I have a problem. When I check the log file after the program runs, I only find one line instead of a few more, because this is only just the program startup. So it should look like this:

(time): Program started
(time): Some stuff happened
(time): Program closed

instead of:

(time): Program closed

Upvotes: 2

Views: 18948

Answers (6)

T. Marra
T. Marra

Reputation: 11

I run some like this

if (!Directory.Exists(path))
 {
    DirectoryInfo di = Directory.CreateDirectory(path);
 }

File.AppendAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, path, folderTarget, fileTarget), "Hello Log");

Upvotes: 1

theHeXaGoNdev
theHeXaGoNdev

Reputation: 19

Thanks for the answers, the File.AppendAllLines works!

Upvotes: 1

Hari Prasad
Hari Prasad

Reputation: 16966

Problem is you are using File.WriteAllLines, which creates a new file each time when called, to fix this problem you you could use File.AppendAllLines which Appends lines to a file, and then closes the file. If the specified file does not exist, File.AppendAllLines method creates a file.

Upvotes: 0

Crowcoder
Crowcoder

Reputation: 11514

File.WriteAllLines will overwrite your file each time you call it. You want to append your text to a file. You could use File.AppendAllLines or File.AppendAllText since it looks like you only have one line to write at a time.

Upvotes: 0

user6522773
user6522773

Reputation:

Use StreamWriter :

using (StreamWriter sw = new StreamWriter(@"C:\Log.txt", true))
{
  sw.WriteLine("Hello Log");
}

Upvotes: 1

Raphaël Vigée
Raphaël Vigée

Reputation: 2045

Your program should be like this :

if (!Directory.Exists(@"C:\Log")) {
    Directory.CreateDirectory(@"C:\Log");
}

...

// Your program runs, you add log lines
string[] start = { DateTime.Now + ": Program Started\n" };
File.AppendAllLines(@"C:\Log\Log.txt", start);
// End add log lines

...

Upvotes: 5

Related Questions