在WebService的帮助下,进行多线程上传文件是非常简单。因此我只做个简单的例子,那么如果想要实现此功能的朋友,可以在我的基础上进行扩展。
首先说说服务器端,只需要提供一个能允许多线程写文件的函数即可,具体代码如下。
[WebMethod]
public bool UploadFileData( string FileName, int StartPosition, byte[] bData )
{
string strFullName = Server.MapPath( "Uploads" ) + @"/" + FileName;
FileStream fs = null;
try
{
fs = new FileStream( strFullName, FileMode.OpenOrCreate,
FileAccess.Write, FileShare.Write );
}
catch( IOException err )
{
Session["ErrorMessage"] = err.Message;
return false;
}
using( fs )
{
fs.Position = StartPosition;
fs.Write( bData, 0, bData.Length );
}
return true;
}
其中“Uploads”是在服务程序所在目录下的一个子目录,需要设置ASPNET用户对此目录具有可写权限。
相对于服务器端来说,客户端要稍微复杂一些,因为要牵扯到多线程的问题。为了更好的传递参数,我用一个线程类来完成。具体如下。
public delegate void UploadFileData( string FileName, int StartPos, byte[] bData );
///
/// FileThread: a class for sub-thread
///
sealed class FileThread
{
private int nStartPos;
private int nTotalBytes;
private string strFileName;
public static UploadFileData UploadHandle;
///
/// Constructor
///
///
///
///
public FileThread( int StartPos, int TotalBytes, string FileName )
{
//Init thread variant
nStartPos = StartPos;
nTotalBytes = TotalBytes;
strFileName = FileName;
//Only for debug
Debug.WriteLine( string.Format( "File name:{0} position: {1} total byte:{2}",
strFileName, nStartPos, nTotalBytes ) );
}
///
/// Sub-thread entry function
///
///
public void UploadFile( object stateinfo )
{
int nRealRead, nBufferSize;
const int BUFFER_SIZE = 10240;
using( FileStream fs = new FileStream( strFileName,
FileMode.Open, FileAccess.Read,
FileShare.Read ) )
{
string sName = strFileName.Substring( strFileName.LastIndexOf( "//" ) + 1 );
byte[] bBuffer = new byte[BUFFER_SIZE];//Init 10k buffer
fs.Position = nStartPos;
nRealRead = 0;