Uploading a file without a new connection being created and closed

Apr 1, 2015 at 6:54 PM
Edited Apr 1, 2015 at 6:55 PM
Why does writing to a stream create a brand new connection and then close it once its finished, even though I already have an open connection. This is causing me a big problem as the server i have to connect to is slow and i have hundreds of files to upload and i have to do it quickly.

Is there a better way, that doesnt do this??
var ftpClient = new FtpClient
{
  Host = ftpAddress,
  Port = ftpPort <= 0 ? 21 : ftpPort,
  SocketKeepAlive = true,
  ConnectTimeout = 1000 * 30,
  ReadTimeout = 1000 * 30,
  DataConnectionType = FtpDataConnectionType.AutoPassive,
  Credentials = new NetworkCredential( username, password )
};

// New connection is created
ftpClient.Connect();

// Another new connection is created
var ftpStream = ftpClient.OpenWrite( uploadRemotePath.ToString() );

var buffer = new byte[ 8 * 1024 ];
int count;
while( ( count = fileStream.Read( buffer, 0, buffer.Length ) ) > 0 )
{
    ftpStream.Write( buffer, 0, count );
}

// Second connection is closed
ftpStream.Close();
Apr 13, 2015 at 11:19 PM
Use
ftpClient.EnableThreadSafeDataConnections = false;