Search code examples
c#socketsfile-transferlan

NetworkStream filename on receiving side


I have been working on this for two days and I can't figure it out. I want to transfer a file over TCP (server sending, client receiving).

The problem that I'm facing is I want to implement a way for the receiving side to know what the file name is of the file it is getting. Working code I have thus far

    public void SendFile(string path, string IP)
    {
        TcpClient client = new TcpClient();
        client.Connect(IP, 1095);

        using (NetworkStream networkStream = client.GetStream())
        using (FileStream fileStream = File.OpenRead(path))
        {
            ASCIIEncoding asci = new ASCIIEncoding();
            byte[] b = asci.GetBytes(path);
            networkStream.Write(b, 0, b.Length);
            networkStream.Flush();
            fileStream.CopyTo(networkStream);
        }
        client.Close();
    }


    private void ListenForFile()
    {
        TcpListener listener = new TcpListener(IPAddress.Any, 1095);
        listener.Start();
        using (TcpClient incoming = listener.AcceptTcpClient())
        using (NetworkStream networkStream = incoming.GetStream())
        using (FileStream fileStream = File.OpenWrite(@pathName + @"\something.extension"))
        {
            networkStream.CopyTo(fileStream);
        }
        listener.Stop();
    }

Solution

  • NetworkStream has no concept of files it's just a class for streaming byte buffers. What you will have to do is come up with some form of protocol to send the filename to the client.

    You could do this by transmitting the length of the filename and filename first followed by the file size and then transmit the actual file contents.

    The client side can read in the filename length, read in the filename, read in the file size then read in the file data.