-------------------------------------------------------------------------

/*****************************************************************
** File Name: frmMain.cs
** Copyright (c) 1999 -2003 
** Creator: FirePhoenix
** Created Date: 2004-11-13 15:24
** Modifier:
** Modify Date:
** Description: 
** Version:1.0
*****************************************************************
*/


Using Directives

namespace WindowsApplication4
{
/// <summary>
/// Copy Large File
/// </summary>

public class frmMain : System.Windows.Forms.Form
{


int totalSize; //Total Size
int position; //Position
const int BUFFER_SIZE = 4096
byte[] buffer;
Stream stream;

private void btnCopy_Click(object sender, System.EventArgs e)
{
string strFile = "";

OpenFileDialog dlg 
= new OpenFileDialog();
if ( dlg.ShowDialog() == DialogResult.OK )
{
strFile 
= dlg.FileName ;
}

else
{
return ;
}


FileStream fs 
= new FileStream( strFile , FileMode.Open , FileAccess.Read ) ;
totalSize 
= (int)fs.Length ;
stream 
= fs;

//Delete file which aready exists.
if ( File.Exists( "c:\\copyedFile.bin" ) )
File.Delete( 
"c:\\copyedFile.bin" );

//Copy file while larger than 4KB.
if ( totalSize > BUFFER_SIZE )
{
buffer 
= new byte[ BUFFER_SIZE ]; 

// Async Invoke
stream.BeginRead( buffer , 0 , BUFFER_SIZE , new AsyncCallback( AsyncCopyFile ) , null ); 
}

else
{
fs.Close();
}


}


/// <summary>
/// Asynchronously copy file
/// </summary>
/// <param name="ar"></param>

private void AsyncCopyFile( IAsyncResult ar )
{
int readedLength ;

// Lock FileStream
lock( stream )
{
readedLength 
= stream.EndRead( ar ); // When stream endread, get readed length
}


// Write to disk
FileStream fsWriter = new FileStream( "C:\\copyedFile.bin" , FileMode.Append , FileAccess.Write );
fsWriter.Write( buffer , 
0 , buffer.Length );
fsWriter.Close();

// Current stream position 
position += readedLength;

// Response UI
MethodInvoker m = new MethodInvoker( SynchProgressBar );
m.BeginInvoke( 
null , null );

if ( position >= totalSize ) // Read over.
{
stream.Close(); 
//Close FileStream 
return ;
}


// Continue to read and write
lock ( stream )
{
int leftSize = totalSize - position;

if ( leftSize < BUFFER_SIZE ) 
buffer 
= new byte[ leftSize ];

stream.BeginRead( buffer , 
0 , buffer.Length , new AsyncCallback( AsyncCopyFile ) , null ); 

}

}


private void SynchProgressBar()
{
this.progressBar1.Maximum = totalSize;
this.progressBar1.Value = position ; 
}


}

}

posted on 2007-02-07 14:24  mbskys  阅读(144)  评论(0)    收藏  举报