FTP上传0字节

Ale*_*ec. 1 c# ftp

情况

我有一些将文件(在本例中通常为 .csv)上传到远程 FTP 站点的代码

代码

    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;
}
Run Code Online (Sandbox Code Playgroud)

问题

该程序成功建立连接,并且似乎正在上传我的文件,但 .csv 为空且文件大小为 0 字节。我的代码中是否有任何内容可能导致此问题?

BAC*_*CON 5

您是否发现您的本地文件也被截断为 0 字节?我认为问题就在这里:

FileStream localFileStream = new FileStream(localFile, FileMode.Create);
Run Code Online (Sandbox Code Playgroud)

FileMode.Open您应该使用或打开文件FileMode.OpenOrCreate。的文档指出FileMode.Create“如果文件已经存在,它将被覆盖。” 而“FileMode.Create相当于请求如果文件不存在,则使用CreateNew;否则,使用Truncate”。