using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Net; namespace PatchSwap { class FileManager { private bool m_IsDownloadSuccessful; public bool IsDownloadSuccessful { get { return m_IsDownloadSuccessful; } set { m_IsDownloadSuccessful = value; } } private bool m_IsDownloading; public bool IsDownloading { get { return m_IsDownloading; } set { m_IsDownloading = value; } } public FileManager() { } public string GetFile( string to, string from, bool deleteOld ) { Stream m_Stream = null; FileStream m_FileStream = null; try { m_IsDownloading = true; if( File.Exists( to ) && deleteOld ) File.Delete( to ); if( !File.Exists( to ) ) { HttpWebRequest request = ( HttpWebRequest )WebRequest.Create( from ); HttpWebResponse response = ( HttpWebResponse )request.GetResponse(); m_Stream = response.GetResponseStream(); byte[] inBuffer = Read( m_Stream, 32768 ); m_FileStream = new FileStream( to, FileMode.OpenOrCreate, FileAccess.Write ); m_FileStream.Write( inBuffer, 0, inBuffer.Length - 1 ); m_FileStream.Close(); m_Stream.Close(); } m_IsDownloadSuccessful = true; m_IsDownloading = false; } catch { m_IsDownloadSuccessful = false; } finally { if( m_FileStream != null ) { m_FileStream.Close(); } if( m_Stream != null ) { m_Stream.Close(); } } return to; } public byte[] Read( Stream stream, int initialLength ) { if( initialLength < 1 ) { initialLength = 32768; } byte[] buffer = new byte[initialLength]; int read = 0; int chunk; while( ( chunk = stream.Read( buffer, read, buffer.Length - read ) ) > 0 ) { read += chunk; if( read == buffer.Length ) { int nextByte = stream.ReadByte(); if( nextByte == -1 ) { return buffer; } byte[] newBuffer = new byte[buffer.Length * 2]; Array.Copy( buffer, newBuffer, buffer.Length ); newBuffer[read] = ( byte )nextByte; buffer = newBuffer; read++; } } byte[] ret = new byte[read]; Array.Copy( buffer, ret, read ); return ret; } } }