Jump to content

Visual C# : Basic Log Files (Console Application)

- - - - -

  • Please log in to reply
5 replies to this topic

#1
Jarryd

Jarryd

    Learning Programmer

  • Members
  • PipPipPip
  • 63 posts

Basic Log File (Console Application)



Difficulty: 2 / 10 : Depending on your knowledge with the C# language.
Assumed Knowledge: Basic knowledge of the try/catch statement.
Information: This tutorial teaches you the basic knowledge of creating logfiles in C#.

One of the simplest, yet very flexible, manners for storing information is within a text file. Such a file allows the storage of data in a human-readable and easily edited format. You can create text files using the .NET framework's StreamWriter class.


Step 1: Starting the Project

Begin this project by creating a new console application in visualo C#.


Posted Image

Step 2: Setting the Console up
For this to work properly, we will need to add System.IO

using System.IO;

I/O is Short for input/output. The term I/O is used to describe any program, operation or device that transfers data to or from a computer and to or from a peripheral device. Every transfer is an output from one device and an input into another.

Step 3: Starting the main Process
We will now need to add two variables.

            string strText;

            StreamWriter logFile;

Information can be written to the StreamWriter, and ultimately the file, using two of the class' methods. The WriteLine method stores an entire line of characters, ending with a carriage return in readiness for a new line. The simplest variation requires a string parameter containing the characters to be written.

and allow the console to read input from the user.

            Console.Write("Name: ");

            strText = Console.ReadLine();

The try/catch statement consists of a try block followed by one or more catch clauses, which specify handlers for different exceptions. When an exception is thrown, the common language runtime (CLR) looks for the catch statement that handles this exception. If the currently executing method does not contain such a catch block, the CLR looks at the method that called the current method, and so on up the call stack. If no catch block is found, then the CLR displays an unhandled exception message to the user and stops execution of the program.

            try

            {


            }

            catch (Exception ex)

            {


            }

The StreamWriter class is a standard class within the System.IO namespace. The class allows character data to be sent to a stream, including a text file, for recording or processing. The character data can be sent with various standardised encoding options such as UTF, Unicode, etc.

            try

            {

                if (!File.Exists("Log.txt"))

                {

                    logFile = new StreamWriter("Log.txt");

                }

                else

                {

                    logFile = File.AppendText("Log.txt");

                }


                logFile.WriteLine(DateTime.Now);

                logFile.WriteLine(strText.ToString());

                logFile.WriteLine();


                Console.WriteLine("Log file saved successfully!");


                logFile.Close();

            }

            catch (Exception ex)

            {

                Console.WriteLine("Error: " + ex.Message);

                goto A;

            }

Often you will need to append text to an existing file, rather than simply overwriting it. An overloaded version of the StreamWriter constructor allows you to specify whether you wish to overwrite or append by adding a Boolean parameter. If the parameter is set to true, text sent to the StreamWriter will be added at the end of the existing information. If set to false, the file will be replaced. In either case, if the specified file does not exist it will be created.


Once all of the required information has been written to the file, you should call the StreamWriter's Close method. This ensures that any buffered information is sent to the stream and frees any resources that are in use. Once the StreamWriter is closed, the text file will be complete.

Finished Source Code:
using System;

using System.IO;


namespace logFiles

{

    class Program

    {

        static void Main()

        {

            string strText;

            StreamWriter logFile;


        A:

            Console.Write("Name: ");

            strText = Console.ReadLine();


            try

            {

                if (!File.Exists("Log.txt"))

                {

                    logFile = new StreamWriter("Log.txt");

                }

                else

                {

                    logFile = File.AppendText("Log.txt");

                }


                logFile.WriteLine(DateTime.Now);

                logFile.WriteLine(strText.ToString());

                logFile.WriteLine();


                Console.WriteLine("Log file saved successfully!");


                logFile.Close();

            }

            catch (Exception ex)

            {

                Console.WriteLine("Error: " + ex.Message);

                goto A;

            }


            Console.Read();

        }

    }

}


Posted Image

Posted Image

#2
ack909

ack909

    Newbie

  • Members
  • Pip
  • 3 posts
It's very useful for me ... Thanks

But, I can not find that Log.txt file.

how to do it?

Edited by ack909, 03 January 2011 - 10:36 PM.


#3
Sp32

Sp32

    Newbie

  • Members
  • PipPip
  • 26 posts
Thanks a lot for this tutorial, my last hdd broke so I am currently installing Visual Studio at this moment but I am glad that I managed to understand the parts of the application in the sections you put them, this was a pretty useful tutorial for me and I'm gonna check your others! Thanks.

Also @ ack909 - I don't know for sure but I'd guess it'd be saved to the location where the console application is located.

#4
delraich

delraich

    Newbie

  • Members
  • Pip
  • 5 posts
thanks

#5
Jarryd

Jarryd

    Learning Programmer

  • Members
  • PipPipPip
  • 63 posts

ack909 said:

It's very useful for me ... Thanks

But, I can not find that Log.txt file.

how to do it?

The file will be saved in your project folder, this is because we have not programmed in a specific location.

and Thanks :)

#6
ack909

ack909

    Newbie

  • Members
  • Pip
  • 3 posts
Thank you for your reply.
:)




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users