Ben
Ben

Reputation: 2715

C# writing to a text file issue

I have a simple enough class that is used to log text to a .txt file im getting the the issue that if the text file does not exist I will get an exception at the point shown in the code. Then the text file appears in the folder after the program has crashed. If I run the program while the log.txt file exists it works perfect.

The code:

class logger
{
        public string source;
        //public logger()
        //{

        //}
        public logger(string source)
        {
            CheckExists(source);
            this.source = source + "log.txt";
        }
        private void CheckExists(string source)
        {
            if (!File.Exists(source + "log.txt"))
            {
                File.Create(source + "log.txt");
            }
        }
        public void WriteToLog(string output)
        {
            try
            {
                using (StreamWriter sw = File.AppendText(this.source))
                {
                    sw.WriteLine(output);
                    sw.Close();
                }
            }
            catch (Exception e)
            {

                //point at which the code breaks;
            }

        }
}

Upvotes: 0

Views: 206

Answers (3)

aharon
aharon

Reputation: 59

Why don't you just use File.AppendAllText

File.AppendAllText(this.source, output);

Upvotes: 5

Yuliam Chandra
Yuliam Chandra

Reputation: 14640

Don't forget to close.

File.Create(source + "log.txt").Close();

Upvotes: 1

Matthew Watson
Matthew Watson

Reputation: 109537

File.Create() leaves the file open until the garbage collector runs, since it returns a FileStream that you are supposed to close. Because it is left open, you are probably getting a sharing violation when you subsequently try to open it.

A better way to create the file is like this:

File.WriteAllText(source + "log.txt", "");

which will close the file afterwards.

Upvotes: 2

Related Questions