I am trying to use StreamWriter to debug a stock trading application, and my code creates the file but doesnt write anything to it. I know the method is being executed because other stuff is happening but the file remains empty.

I think I am missing something when I create the StreamWriter:

 public class SterlingDebug : ResponseTemplate
    {   
StreamWriter writer = new StreamWriter(@"C:\Documents and Settings\ecoarsey\SterlingIssue10222010.txt");

int i = 0;
     public override void GotTick(Tick tick)
        {
            //StreamWriter writer = new StreamWriter(fs);
            //print 10 ticks
            i++;
            if (i < 11)
            {
                D(tick.ToString());
                writer.WriteLine("Tick #: {0}",i);
            }           

        }    
    }

Edited 3 Years Ago by Reverend Jim: Fixed formatting

Please place your code inside code brackets so we can read the code properly.

The best way to do what you're trying to do is with a 'using' statement:

public class SterlingDebug : ResponseTemplate
{
	private StreamWriter writer;
	private int i = 0;
	
	public override void GotTick(Tick tick)
	{
		//print 10 ticks
		if (++i < 11)
		{
			D(tick.ToString());
			using (writer = new StreamWriter(@"C:\Documents and Settings\ecoarsey\SterlingIssue10222010.txt"))
			{
				writer.WriteLine("Tick #: {0}", i);
			}
		}
	}
}

Edited 6 Years Ago by Kimpl: n/a

There are several things wrong with the code (and Kimpl left them in and added a new one).

First, an if statement is not a loop. It will only execute one time then your method will end.

Second, you never flush the stream. File based streams buffer data and only write when the buffer is full (because IO is slow this helps keep your program fast). So you need to use flush. using will call the Dispose() method, which will automatically flush the stream.

Kimpl's mistake is that he places the opening of the stream inside what is supposed to be the loop. It should be outside.

I would also change the iteration variable to increment after, that way you can see the 10 count and it makes more sense than the 11:

public class SterlingDebug : ResponseTemplate {
    private StreamWriter writer;
    private int i = 0;
       
    public override void GotTick(Tick tick) {
        using (writer = new StreamWriter(@"C:\Documents and Settings\ecoarsey\SterlingIssue10222010.txt")) {
        //print 10 ticks
            while (i++ < 10) {
                D(tick.ToString());
                writer.WriteLine("Tick #: {0}", i);
            }
        }
    }
}

Edited 6 Years Ago by Momerath: n/a

I didn't read the code properly, thus not realising it was supposed to be a loop. My apologies.

This article has been dead for over six months. Start a new discussion instead.