Search code examples
c#tcpclientstreamwriter

Error working with both TcpClient and StreamWriter


My goal is to write a simple program that can get some text streaming from a TCP server and to write it into a .txt file (or a DB, but for now txt file is OK). But... if I try to run the code below it simply doesn't write anything into the file. The file remain empty, it only works if I remove the while loop: If I remove it, the program writes the string "ciao" in the file. Otherwise he doesn't even write that and doesn't throw any exceptions. It's driving me crazy.... Anyway, am I doing it right? Is there a better way to do it?

Thanks!!! :)

public static void Main()
{
    TcpClient client = new TcpClient();

    Console.WriteLine("In connessione.....");

    client.Connect("192.168.5.200", 4001);

    Console.WriteLine("Connesso");

    StreamReader sr = new StreamReader( client.GetStream() );

    string data = sr.ReadLine();

    using (StreamWriter sw = File.AppendText(@"C:\Users\Public\Documents\test.txt"))
    {
        sw.WriteLine("ciao");

        while (data != null)
        {
            Console.WriteLine(data);
            sw.WriteLine(data);
            data = sr.ReadLine();
        }
    }

}

Solution

  • it only works if I remove the while loop

    It seems to me the problem is just that the file stays in edit mode (and the written text is buffered) and never gets written away (on close/dispose).

    Try what happens if you terminate the line reading after a few lines. Does it get written to file? I am sure it is. Flushing your buffer is an option to get intermediate results written to the file, so put this after sw.WriteLine(data);:

    sw.Flush();