gpt4 book ai didi

c# - FTP 上传 0 字节

转载 作者:太空宇宙 更新时间:2023-11-03 21:16:38 24 4
gpt4 key购买 nike

情况

我有一些代码可以上传文件,在这种情况下通常是 .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 为空且文件大小为 0 字节。我的代码中是否有任何可能导致此问题的内容?

最佳答案

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

FileStream localFileStream = new FileStream(localFile, FileMode.Create);

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

关于c# - FTP 上传 0 字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33785245/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com