Alec.
Alec.

Reputation: 5535

FTP uploading 0 bytes

Situation

I have some code that uploads a file, usually .csv in this case to a remote FTP site

Code

    try
    {
        /* Create an FTP Request */
        ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + remoteFile);
        /* Log in to the FTP Server with the User Name and Password Provided */
        ftpRequest.Credentials = new NetworkCredential(user, pass);
        /* When in doubt, use these options */
        ftpRequest.UseBinary = false;
        ftpRequest.UsePassive = false;
        ftpRequest.KeepAlive = true;
        /* Specify the Type of FTP Request */
        ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
        /* Establish Return Communication with the FTP Server */
        ftpStream = ftpRequest.GetRequestStream();
        /* Open a File Stream to Read the File for Upload */
        FileStream localFileStream = new FileStream(localFile, FileMode.Create);
        /* Buffer for the Downloaded Data */
        byte[] byteBuffer = new byte[bufferSize];
        int bytesSent = localFileStream.Read(byteBuffer, 0, bufferSize);
        /* Upload the File by Sending the Buffered Data Until the Transfer is Complete */
        try
        {
            while (bytesSent != 0)
            {
                ftpStream.Write(byteBuffer, 0, bytesSent);
                bytesSent = localFileStream.Read(byteBuffer, 0, bufferSize);
            }
        }
        catch (Exception ex) { Console.WriteLine(ex.ToString()); }
        /* Resource Cleanup */
        localFileStream.Close();
        ftpStream.Close();
        ftpRequest = null;
    }
    catch (Exception ex) { Console.WriteLine(ex.ToString()); }
    return;
}

Issue

The program makes a connection successfully, and appears to upload my file, but the .csv is empty and the filesize is 0 bytes. Is there anything in my code that could cause this?

Upvotes: 1

Views: 4774

Answers (1)

Lance U. Matthews
Lance U. Matthews

Reputation: 16612

Are you finding that your local file is being truncated to 0 bytes, too? I think the issue is here:

FileStream localFileStream = new FileStream(localFile, FileMode.Create);

You should be opening the file with FileMode.Open or FileMode.OpenOrCreate. The documentation for FileMode.Create states "If the file already exists, it will be overwritten." and "FileMode.Create is equivalent to requesting that if the file does not exist, use CreateNew; otherwise, use Truncate".

Upvotes: 5

Related Questions