上传文件到FTP

利用 FtpWebRequest 类实现上传文件到FTP. 先在本机建一个FTP站点,建在别的机器上也行.....
将 Ftp 的地址和帐号和密码等相关信息写 在 Web.config  , 方便管理 ,  这里利用 FileUpload 的 FileContent 属性 , 将文件流写到FTP服务器.
通过一个枚举来记录文件存储方式
enum  FileUpLoadMethod
{
    file 
=   1  ,
    ftp 
=   2
}

下面重要的是利用 FtpWebRequest  类实现和FTP服务器的通讯.
FtpWebRequest request;
try
{
    request 
=  ( FtpWebRequest )WebRequest.Create( GetUri( server , port , path ,  " FTP "  ) );
}
catch
{
    backMsg 
=   " 创建FTP请求失败 " ;
    
return   false ;
}
request.Method 
=  WebRequestMethods.Ftp.UploadFile;
if ( isAnoymous )
{
    request.Credentials 
=   new  NetworkCredential(  " anonymous "  , userEmail );
}
else   if ! string .IsNullOrEmpty( domain ) )
{
    request.Credentials 
=   new  NetworkCredential( username , password , domain );
}
else
{
    request.Credentials 
=   new  NetworkCredential( username , password );
}

建立好 FtpWebRequest 对象后 ,  剩下的事情就是将文件流写入FTP服务器了
Stream requestStream  =   null ;
bool  success  =   false ;
request.ContentLength 
=  inputStream.Length;
try
{
    requestStream 
=  request.GetRequestStream( );
    success 
=   true ;
}
catch ( Exception ex )
{
    success 
=   false ;
    
if ( ex  is  WebException )
    {
        WebException wex 
=  ex  as  WebException;
        
if ( ( ( FtpWebResponse )wex.Response ).StatusCode  ==  FtpStatusCode.ActionNotTakenFileUnavailable )
            backMsg 
=   string .Format(  " 指定的文件路径不存在,错误如下:\n\t{0} "  , ex.Message );
    }
    
else   if ( ex  is  ProtocolViolationException )
        backMsg 
=   string .Format(  " Protocol wrong:\n{0}\n "  , ex.Message );
    
else
        backMsg 
=   string .Format(  " InvalidOperation:\n{0}\n "  , ex.Message );
}
if ( success )
{
    
try
    {
        
int  count  =   0 ;
        
byte [ ] buffer  =   new   byte [ 1024 ];
        
while ( ( count  =  inputStream.Read( buffer ,  0  ,  1024  ) )  >   0  )
        {
            requestStream.Write( buffer , 
0  , count );
        }
    }
    
catch ( Exception ex )
    {
        success 
=   false ;
        backMsg 
=   string .Format(  " Write UploadStream wrong:\n{0} "  , ex.ToString( ) );
    }
    
finally
    {
        requestStream.Close( );
        requestStream.Dispose( );
    }
}
在这里可以下载完整的 DEMO

转载于:https://www.cnblogs.com/doll-net/archive/2007/09/08/886387.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值