0

I am trying to send *.pdf file and save it on second machine. Im using following code to send:

IPHostEntry ipHost = Dns.GetHostEntry("127.0.0.1");
IPAddress  ipAddr = ipHost.AddressList[0];
IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, 11000);

Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

client.Connect(ipEndPoint);

Console.WriteLine("Sending {0} to the host.", fileName);
client.SendFile(file);

client.Shutdown(SocketShutdown.Both);
client.Close();

And following to save file:

var listener = new TcpListener(IPAddress.Loopback, 11000);
listener.Start();
while (true)
{
    using (var client = listener.AcceptTcpClient())
    using (var stream = client.GetStream())
    using (var output = File.Create("C:/ODEBRANE/result.pdf"))
    {
        Console.WriteLine("Client connected. Starting to receive the file");

        // read the file in chunks of 1KB
        var buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
        {
            output.Write(buffer, 0, bytesRead);
        }
    }
}

Now, question is, how can I get file name same as on client side? without renaming it to "result"? Is there any possibility to send that name with file and use it on server side?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
rafixwpt
  • 155
  • 3
  • 9
  • 1
    You will have to decide a communication format, for example, the first 512 bytes will contain the filename and the following data will be the file content. Obviously you'll have to use the Send method of the Socket class – Matteo Umili May 25 '15 at 19:14
  • I think you need to design more your application. Read this article about how to serialize & de-serialize objects http://net-informations.com/faq/net/serialization.htm – MrAlex6204 May 25 '15 at 19:36
  • This linke might help - http://snippetbank.blogspot.com/2014/04/csharp-client-server-file-transfer-example-1.html – Ravindra Gullapalli Oct 18 '20 at 04:30

1 Answers1

0

The "file header" can be introduced to solve the problem. The "file header" data structure should contain the required information (at least, file size, and, for example, file name). Let's consider the following flow to demonstrate the idea:

  1. The Client sends the "file header" (filled appropriately) first and, after that, the file content.
  2. The Server receives the "file header" and, having the knowledge of file size, receives the file content.