如何使用c#使用FTP上传文件

时间:2015-10-13 17:42:51

标签: c# ftp

我想将文件(byte = 2000)从本地上传到ftp服务器,但是我找到一个空白文件(0字节)

public void upload(string remoteFile, string localFile)
{
    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 = true;
        ftpRequest.UsePassive = true;
        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 */
        //int bytesRead;
        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;
}

1 个答案:

答案 0 :(得分:2)

您正在使用FileMode.Create打开本地文件;但是,正如MSDN documentation所述,FileMode.Create

  

指定操作系统应创建新文件。如果   文件已存在,将被覆盖。这需要   FileIOPermissionAccess.Write权限。 FileMode.Create 是等效的   要求如果文件不存在,请使用CreateNew;   否则,请使用截断。如果文件已存在但是隐藏了   文件,抛出一个UnauthorizedAccessException异常。

因此,您正在从零字节文件中读取数据;在这种情况下,将零字节发送到FTP服务器并不奇怪。