I used this code to download files from the server, maybe it is useful to you ...
private bool DownLoadFile(string pstrFileName, string pstrFilePath, long plngFileSize)
{
try
{
string strNewFileSize = CalcFileSize(plngFileSize);
int numIterations = 0;
Offset = 0;
long webConfigSetting = this.mobjService.GetMaxRequestLength();
this.MaxRequestLength = Math.Max(1, (webConfigSetting * 1024) - (2 * 1024));
if (File.Exists(pstrFilePath))
{
Offset = new FileInfo(pstrFilePath).Length;
if (Offset == plngFileSize)
Offset = 0;
}
if (Offset == 0 && !File.Exists(pstrFilePath))
File.Create(pstrFilePath).Close();
lblFileName.Text = pstrFileName.Substring(0, pstrFileName.LastIndexOf(".")).Replace("&", "&&");
using (FileStream fs = new FileStream(pstrFilePath, FileMode.OpenOrCreate, FileAccess.Write))
{
pbrSummary.Maximum = (int)plngFileSize;
fs.Seek(Offset, SeekOrigin.Begin);
while (Offset < plngFileSize)
{
int currentIntervalMod = numIterations % this.ChunkSizeSampleInterval;
if (currentIntervalMod == 0)
StartTime = DateTime.Now;
else if (currentIntervalMod == 1)
CalcAndSetChunkSize(plngFileSize);
try
{
byte[] Buffer = mobjService.DownloadChunk(pstrFileName, Offset, ChunkSize);
fs.Write(Buffer, 0, Buffer.Length);
Offset += Buffer.Length;
}
catch (Exception ex)
{
if (ex.Message.Contains("File not found") || NumRetries++ >= MaxRetries)
{
fs.Close();
return false;
}
}
numIterations++;
}
}
return true;
}
catch (Exception Exc)
{
throw (Exc);
}
}
private void CalcAndSetChunkSize(long plngFileSize)
{
double transferTime = DateTime.Now.Subtract(this.StartTime).TotalMilliseconds;
double averageBytesPerMilliSec = this.ChunkSize / transferTime;
double preferredChunkSize = averageBytesPerMilliSec * this.PreferredTransferDuration;
this.ChunkSize = (int)Math.Min(this.MaxRequestLength, Math.Max(4 * 1024, preferredChunkSize)) * 10;
}
source
share