PDA

View Full Version : C# write to file write class


barkermn01
05-18-2009, 01:47 PM
Hi, for some reason the system.IO wont work in a class,

This is my class now when i call log.start() it works and adds the text, but when i call log.WriteLine my application freezes and i get this error and debug info,

Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.
at CRM_Server_TEST.log.WriteLine(String output)
at CRM_Server_TEST.Program.showHelp()
at CRM_Server_TEST.Program.inputText()
at CRM_Server_TEST.Program.Main(String[] args)


class log
{
public TextWriter tw;

public void start()
{
tw = new StreamWriter("logs.log");
tw.WriteLine("Logs started at " + DateTime.Now);
}

public void end()
{
tw.Close();
}

public void WriteLine(string output)
{
tw.WriteLine(output);
}
}

Brandoe85
05-18-2009, 05:52 PM
If you don't call start() before WriteLine() then tw will never be set, since you're setting it in start():

tw = new StreamWriter("logs.log");


Make sure tw is set (or set it) before you call any of it's methods. Good luck;

kokjj87
05-18-2009, 06:12 PM
This should be a working example(not tested..), make sure you call log.end(), orelse it wouldn't write to stream

using System;
using System.IO;

public class Test
{
public static void Main()
{
log t = new log();
t.start();
t.WriteLine("hohoho");
t.end();
Console.ReadLine();
}
}

class log
{
public TextWriter tw;

public void start()
{
tw = new StreamWriter("logs.log");
//since you are going to create a method for writing to file, might as well use it
this.WriteLine("Logs started at " + DateTime.Now);
}

public void end()
{
tw.Close();
}

public void WriteLine(string output)
{
tw.WriteLine(output);
}
}