场合
我有一些代码可以上传文件,在这种情况下通常是.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;
}
问题
程序成功建立连接,并且似乎上传了我的文件,但.csv为空,filesize为0字节。我的代码中是否有任何可能导致此问题的内容?
答案 0 :(得分:4)
您是否发现本地文件也被截断为0字节?我认为这个问题在这里:
FileStream localFileStream = new FileStream(localFile, FileMode.Create);
您应该使用FileMode.Open
或FileMode.OpenOrCreate
打开文件。 documentation for FileMode.Create
状态“如果文件已存在,则会被覆盖。”并且“FileMode.Create等同于请求如果文件不存在,则使用CreateNew;否则,使用Truncate”。