Search code examples
c#c#-4.0memorystreambinarywriter

Clear binarywriter with memorystream


I´ve a binarywriter with a memorystream, and I need to clear it if one condition happens:

public void Execute() {
    MemoryStream memoryStream = new MemoryStream();
    BinaryWriter writer = new BinaryWriter(memoryStream);
    Log log = new Log(writer);
    log.Write("OK1");
    ...

    // If condition
    memoryStream = new MemoryStream();
    ...
    log.Write("OK2");
    ...
}

public class Log {

    private BinaryWriter log;

    public Log(BinaryWriter bw)
    {
        log = bw;
    }

    public void write(string msg)
    {
        log.Write(msg);
    }
}

But the problem is memorystream is empty. I ´ve tried creating a new BinaryWriter again:

public void Execute() {
    MemoryStream memoryStream = new MemoryStream();
    BinaryWriter writer = new BinaryWriter(memoryStream);
    Log log = new Log(writer);
    log.Write("OK1");
    ...

    // If condition
    memoryStream = new MemoryStream();
    writer = new BinaryWriter(memoryStream);
    ...
    log.Write("OK2");
    ...
}

public class Log {

    private BinaryWriter log;

    public Log(BinaryWriter bw)
    {
        log = bw;
    }

    public void write(string msg)
    {
        log.Write(msg);
    }
}

But both BinaryWriter and MemoryStream are empry.

How can I clear binarywriter with memorystream? I need to write the final content of memorystream to a file.

Thanks!


Solution

  • Do you mean you want to write to a different MemoryStream? You have passed the reference of the old writer to the Log so the Log instance holds the reference. Altering the writer variable after that won't take effect. You need to either

    1. Create a new Log and pass the new writer to it
    2. Expose a method of Log to allow manipulation of the BinaryWriter kept by the object from outside