i am trying to download a image file using ftp, on every code i have looked up a fixed sized array is being used (as bufferSize is being used in below code), how can i efficiently work around this and resize the buffer at run time as i am dealing with images of significant size.
string[] ftpInfo = (string[])e.Argument;
string uri = String.Format("ftp://{0}/{1}/images/{2}", ftpInfo[1], ftpInfo[2], ftpInfo[5]);
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(uri);
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.UseBinary = true;
request.Credentials = new NetworkCredential(ftpInfo[3], ftpInfo[4]);
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream ftpStream = response.GetResponseStream();
long cl = response.ContentLength;
int bufferSize = 4096; //Image file cannot be greater than 40 Kb
int readCount = 0;
byte[] buffer = new byte[bufferSize];
MemoryStream memStream = new MemoryStream();
readCount = ftpStream.Read(buffer, 0, bufferSize);
while (readCount > 0)
{
memStream.Write(buffer, 0, readCount);
readCount = ftpStream.Read(buffer, 0, bufferSize);
}
response.Close();
You won’t have any overflow issues.
ensures that you won’t read more than ‘bufferSize’.
So you read a chunk of size up to bufferSize, write it to the
MemoryStreamand continue reading the next chunk.If you’re concerned about the size of data you write to the
MemoryStreamyou can use anotherStream, for exampleFileStream.