如何使用c#上传FTP文件

本文关键字:FTP 文件 上传 何使用 | 更新日期: 2023-09-27 18:17:35

我想从本地上传文件(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;
}

如何使用c#上传FTP文件

您正在使用FileMode.Create打开本地文件;然而,正如MSDN文档所述,FileMode.Create

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

因此,你正在从一个零字节文件中读取;在这种情况下,向FTP服务器发送零字节也就不足为奇了。