Search code examples
c#filesocketsiofilestream

Writing to file works in "step in" debug mode only?


Hello everyone I have a problem concerning my "FTP" application I am attempting to create. I have built a client in C# and my server in C. For my client I am using visual studio 2015. My code executes perfectly when i use the "step-in/step-out" debug mode features. The problem occurs when the client attempts to download a file. The server sends the entire contents of the file and the client receives all of these contents but for some reason only about 70% of the file is written to the FileStream.

my code is below:

public void download(string baseCom,string downloadPlace)
        {
            //baseCom is the main command
            //downloadPlace is location to download file from including name

            sendCommand(baseCom);
            FileStream myStream = File.Create(downloadPlace);
            int bytesRead = 0;
            byte[] myByte = new byte[1024];
            do
            {
                bytesRead = ourSock.Receive(myByte, myByte.Length, 0);
                myStream.Write(myByte, 0, bytesRead);



            } while ((bytesRead > 0) && (bytesRead == 1024)) ;


            myStream.Flush();
            myStream.Close();
            }

I am new to C# and network programming in general so I appreciate all of you help. Part of me believes that somehow when running the program regularly perhaps some data remains "left-over" in the socket-stream.


Solution

  • ((bytesRead > 0) && (bytesRead == 1024))
    

    seems to be the problem here.

    Requesting a read operation for 1024 bytes does not guarantee that you will get 1024 bytes.

    You can get any number of bytes between 0 and 1024 (0 means end of transmission), and when this is the case, (let's say the read buffer has only 768 bytes) you just stop reading.

    So, if this happens when half of the file has been received (all by 1024 byte reads), you will not have the remaining half and save what you fetched so far.

    Please change it to:

    while (bytesRead > 0);