I am trying to upload a 4 GB zip file via below code.
The same code is working for a smaller files, but it is not working with a large file. I think the exception is generated while closing the FileStream.
I am getting this error:
Message:The underlying connection was closed: An unexpected error occurred on a receive. Stacktrace: at System.Net.FtpWebRequest.SyncRequestCallback(Object obj) at System.Net.FtpWebRequest.RequestCallback(Object obj) at System.Net.CommandStream.Dispose(Boolean disposing) at System.IO.Stream.Close() at System.IO.Stream.Dispose() at System.Net.ConnectionPool.Destroy(PooledStream pooledStream) at System.Net.ConnectionPool.PutConnection(PooledStream pooledStream, Object owningObject, Int32 creationTimeout, Boolean canReuse) at System.Net.FtpWebRequest.FinishRequestStage(RequestStage stage) at System.Net.FtpWebRequest.SyncRequestCallback(Object obj) at System.Net.FtpWebRequest.RequestCallback(Object obj) at System.Net.CommandStream.Abort(Exception e) at System.Net.CommandStream.CheckContinuePipeline() at System.Net.FtpWebRequest.DataStreamClosed(CloseExState closeState) at System.Net.FtpDataStream.System.Net.ICloseEx.CloseEx(CloseExState closeState) at System.Net.FtpDataStream.Dispose(Boolean disposing) at System.IO.Stream.Close() at System.IO.Stream.Dispose() at BackupUtility.Program.UploadFileToFTP(String source)
My FTP code is:
private static bool UploadFileToFTP(string source)
{
try
{
String sourcefilepath = source; // e.g. "d:/test.docx"
String ftpurl = "myftpurl";
String ftpusername = "ftpusername"; // e.g. username
String ftppassword = "ftppassword"; // e.g. password
string ftpfullpath = "mylocalftpFilePath";
Console.WriteLine("Before Request. ftpfullpath:" + ftpfullpath);
// Console.ReadLine();
FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpfullpath);
ftp.Credentials = new NetworkCredential(ftpusername, ftppassword);
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
ftp.KeepAlive = true;
ftp.UseBinary = true;
ftp.Timeout = 6000000;
ftp.Method = WebRequestMethods.Ftp.UploadFile;
FileStream fs = File.OpenRead(source);
byte[] buffer = new byte[8192];
using (Stream ftpstream = ftp.GetRequestStream())
{
//Stream ftpstream = ftp.GetRequestStream();
int read = 0;
while ((read = fs.Read(buffer, 0, buffer.Length)) != 0)
{
ftpstream.Write(buffer, 0, read);
}
ftpstream.Flush();
}
fs.Read(buffer, 0, buffer.Length);
fs.Close();
}
catch (Exception ex)
{
return false;
}
return true;
}