Question

I have a question regarding the CopyTo() method of the Stream class:

https://learn.microsoft.com/en-us/dotnet/api/system.io.stream.copyto

This approach works for small file circa 15kb as I tried it, but anything higher (I tested with 2mbs, 4 mbs and so on) and it just hangs on the CopyTo() method. Can't really figure out why.

Code sample:


Server's handle client :

public void HandleClient(object c)
{
    string path = "some path";
    using (TcpClient client = (TcpClient)c)
    {
        using (NetworkStream netStream = client.GetStream())
        {
            using (FileStream fileStream = new FileStream(path, FileMode.Create))
            {
                netStream.CopyTo(fileStream);
            }
        }
    }
}

Client send :

public void Send()
{
    IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Parse("some address"), 12345);
    string path = "some path";

    using (TcpClient client = new TcpClient(remoteEndPoint))
    {
        using (NetworkStream netStream = client.GetStream())
        {
            using (FileStream fileStream = new FileStream(path, FileMode.Open))
            {
                fileStream.CopyTo(netStream);
            }
        }
    }
}

P.s. As I research my way into Network Programming, I often find people advising other people to switch to WCF for this kind of tasks since, apparently, WCF makes everything a lot easier. What do you guys suggest and could you provide some links for a WCF noob that would be useful in modeling a LAN file sharing application since that's what my goal is?

Was it helpful?

Solution

I managed to solve the CopyTo() issue. The problem was that I was sending the file on the main thread so the whole application just chocked for larger files that took more than an instant to transfer.

Put the sending operation in a separate thread and tested sending up to 3 GB, works as it should. Now, is there any way I could track the progress of the CopyTo() operation? Seems to me that I can't and that I should do manual transfer if I want to track the progress.

Thanks to everyone involved :)

OTHER TIPS

I'm not sure you can do a CopyTo with a file larger than the buffer size. Maybe, you can try to write it by splitting your file every buffer size.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top