Search code examples
c#uploadftpfilestream

Uploading to FTP server results to zero byte size in c#


public void upload(string remoteFile, string localFile)
{
    MessageBox.Show(remoteFile);
    MessageBox.Show(localFile);
    try
    {
        ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + remoteFile);
        ftpRequest.Credentials = new NetworkCredential(user, pass);
        ftpRequest.UseBinary = true;
        ftpRequest.UsePassive = true;
        ftpRequest.KeepAlive = true;
        ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
        ftpStream = ftpRequest.GetRequestStream();
        FileStream localFileStream = new FileStream(localFile, FileMode.Create);
        byte[] byteBuffer = new byte[bufferSize];
        int bytesSent = localFileStream.Read(byteBuffer, 0, bufferSize);
        try
        {
            while (bytesSent != 0)
            {
                ftpStream.Write(byteBuffer,0, bytesSent);
                bytesSent = localFileStream.Read(byteBuffer, 0, bufferSize);
            }
        }
        catch (Exception ex)
        { 
            MessageBox.Show(ex.ToString());
        }
        localFileStream.Close();
        ftpStream.Close();
        ftpRequest = null;
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
    return;
}

Please check the code above in which I have use upon my code.


Solution

  • this is now solve, I have just replace FileMode.Create to FileMode.Open