在c#中上传到FTP服务器结果为零字节大小

时间:2016-12-14 04:56:36

标签: c# upload ftp filestream

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;
}

请检查我在代码中使用的上述代码。

1 个答案:

答案 0 :(得分:0)

现在解决了,我已经将FileMode.Create替换为FileMode.Open