Nick Williams

Nick Williams

  • NA
  • 1
  • 9.8k

C# Streamwriter Flush()

Jun 26 2012 6:11 AM
Hi,

I have a problem which I imagine is fairly simple to solve. I've written a class which takes an input of a file path and a message. The message will then be written to the file (or if the file doesnt exist its created and the message written). 

However the file is not written to (or created if it didnt exist) until the entire program is quit. Is there a way to make the changes appear while the program is still running??

Heres the class;

[code] public class LogFileWatcher
    {
        public LogFileWatcher()
        {
        }
        
        public void WriteFile(string stFilePath, string stMessage)
        {
        

        // This text is added only once to the file.
        if (!File.Exists(stFilePath)) 
        {
            // Create a file to write to.
            using (StreamWriter sw = File.CreateText(stFilePath)) 
            {
                string stOpened1 = "-------------------------------------------------";
                string stOpened2 = "-----------------Process Started-----------------";
                string stOpened3 = "-------------------------------------------------";
                sw.WriteLine(stOpened1);
                sw.WriteLine(stOpened2);
                sw.WriteLine(stOpened3);
                sw.Flush();
                sw.Close();
            }         
        }
        
       
  
    
        // This text is always added if the file exists, making the file longer over time
        // if it is not deleted.
        using (StreamWriter sw = File.AppendText(stFilePath)) 
        {
            sw.WriteLine(stMessage+ "\t" + DateTime.Now.ToShortDateString()
                               + "\t" + DateTime.Now.ToLongTimeString());
            sw.Flush();
            sw.Close();
           }
        
        
        

    
        }
    }[\code]