public class FTPHelper
{
public FTPHelper(NetworkCredential credentials)
{
this.Credentials = credentials;
}
#region Fields
// 2M bytes.
public const int MaxCacheSize = 2097152;
// 2K bytes.
public const int BufferSize = 2048;
public NetworkCredential Credentials { get; set; }
#endregion Fields
#region Public Methods
///
/// Download file. FTP Uri eg.ftp://localhost/TestDiretory/ (In this,Last '/' must be include)
///
///
///
///
public void DownloadFile(string urlStr, string fileName,string savePath)
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(urlStr + fileName);
request.Method = WebRequestMethods.Ftp.DownloadFile;
if (!Directory.Exists(savePath))
{
Directory.CreateDirectory(savePath);
}
string destPath = Path.Combine(savePath, fileName);
request.Credentials = Credentials;
FtpWebResponse response = null;
Stream responseStream = null;
MemoryStream downloadCache = null;
try
{
response = (FtpWebResponse)request.GetResponse();
responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
// Cache data in memory.
downloadCache = new MemoryStream(MaxCacheSize);
byte[] downloadBuffer = new byte[BufferSize];
int bytesSize = 0;
int cachedSize = 0;
// Download the file until the download is completed.
while (true)
{
// Read a buffer of data from the stream.
bytesSize = responseStream.Read(downloadBuffer, 0,
downloadBuffer.Length);
// If the cache is full, or the download is completed, write
// the data in cache to local file.
if (bytesSize == 0
|| MaxCacheSize < cachedSize + bytesSize)
{
try
{
// Write the data in cache to local file.
WriteCacheToFile(downloadCache, destPath, cachedSize);
// Stop downloading the file if the download is paused,
// canceled or completed.
if (bytesSize == 0)
{
break;
}
// Reset cache.
downloadCache.Seek(0, SeekOrigin.Begin);
cachedSize = 0;
}
catch (Exception ex)
{
throw ex;
}
}
// Write the data from the buffer to the cache in memory.
downloadCache.Write(downloadBuffer, 0, bytesSize);
cachedSize += bytesSize;
}
}catch(Exception ex)
{
throw new Exception("下?载?文?件t失§败ü!?",ex);
}
finally
{
if (response != null)
{
response.Close();
}
if (responseStream != null)
{
responseStream.Close();
}
if (downloadCache != null)
{
downloadCache.Close();
}
}
}
#endregion Public Methods
#region Private Methods
///
/// Write the data in cache to local file.
///
private void WriteCacheToFile(MemoryStream downloadCache, string downloadPath,
int cachedSize)
{
using (FileStream fileStream = new FileStream(downloadPath,
FileMode.Create))
{
byte[] cacheContent = new byte[cachedSize];
downloadCache.Seek(0, SeekOrigin.Begin);
downloadCache.Read(cacheContent, 0, cachedSize);
fileStream.Write(cacheContent, 0, cachedSize);
}
}
#endregion Private Methods
}