关于作者

姓名:

性别:男

出生日期:--

地区:

联系电话:

QQ:--

婚否:保密
用户名:chang110cn
笔名:chang110cn
地区:
行业:其他

日历  

快速登录

+ 用户名:
+ 密 码:

在线留言



访问统计:
文章个数:24
评论个数:7
留言条数:5




Powered by BlogDriver 2.1

chang110cn的博客

 

欢迎访问chang110cn的博客!

春花,秋月,夏雨,冬雪!
我在你心中!
别忘了我是你的朋友!

文章

Vcastr 2.2 flv 网络播放器

Vcastr2.2 是一款FLV网络播放器,可以用于各种新闻系统或者blog系统,Vcastr 拥有众多特点和自定义设置,经过不断升级修正,已经具备用户需要的大多数基本功能。


使用方法

1.js嵌入

方法一,直接copy下面代码,修改其中的 swf_width,swf_height,files,texts 参数
<script type="text/javascript">
var swf_width=240
var swf_height=240
var texts='幸福的脚丫预告片|变形金刚预告片|江南MV|魔兽世界-晚安部落'
var files='http://www.ruochi.com/product/vcastr/flv/happy_feet.flv|http://www.transformersmovie.com/transformers_640.flv|http://www.ruochi.com/product/vcastr/flv/江南.flv|http://www.ruochi.com/product/vcastr/flv/晚安部落.flv'
document.write('<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" width="'+ swf_width +'" height="'+ swf_height +'">');
document.write('<param name="movie" value="http://www.ruochi.com/product/vcastr2/vcastr22.swf"><param name="quality" value="high">');
document.write('<param name="menu" value="false"><param name="allowFullScreen" value="true" />');
document.write('<param name="FlashVars" value="vcastr_file='+files+'&vcastr_title='+texts+'">');
document.write('<embed src="http://www.ruochi.com/product/vcastr2/vcastr22.swf" allowFullScreen="true" FlashVars="vcastr_file='+files+'&vcastr_title='+texts+'" menu="false" quality="high" width="'+ swf_width +'" height="'+ swf_height +'" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />'); document.write('</object>');
</script>

2,方法二,简单直接传递影片地址

其中
vcastr_flie =http://www.ruochi.com/product/vcastr/flv/happy_feet.flv|http://www.ruochi.com/product/vcastr/flv/江南.flv|http://www.ruochi.com/product/vcastr/flv/晚安部落.flv
直接给出flv文件地址,多个使用|分开

<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0" width="240" height="180">
<param name="movie" value="http://www.ruochi.com/product/vcastr2/vcastr22.swf">
<param name="quality" value="high">
<param name="allowFullScreen" value="true" />
<param name="FlashVars" value="vcastr_file=http://www.ruochi.com/product/vcastr/flv/happy_feet.flv" />
<embed src="http://www.ruochi.com/product/vcastr2/vcastr22.swf" allowFullScreen="true" FlashVars="vcastr_file=http://www.ruochi.com/product/vcastr/flv/happy_feet.flv" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="240" height="180"></embed>
</object>


3,方法三,读取影片xml

其中/product/vcastr2/vcastr2.swf?vcastr_xml_url =http://www.ruochi.com/product/vcastr/vcastr.xml
是播放列表的xml地址

<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0" width="240" height="120">
<param name="movie" value="http://www.ruochi.com/product/vcastr2/vcastr22.swf">
<param name="quality" value="high">
<param name="allowFullScreen" value="true" />
<param name="FlashVars" value="vcastr_xml=http://www.ruochi.com/product/vcastr2/vcastr.xml" />
<embed src="http://www.ruochi.com/product/vcastr2/vcastr22.swf" allowFullScreen="true" FlashVars="vcastr_xml=http://www.ruochi.com/product/vcastr2/vcastr.xml" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="240" height="120"></embed>
</object>

4.高级选项


<param name="FlashVars" value="*" />

FlashVars="*"


在以上2处*部分添加参数,使用 参数=值 的格式,多个参数用&连接,参数数量不限制

例如

value="vcastr_file=http://www.transformersmovie.com/transformers_640.flv&vcastr_title=变形金刚预告片&BarColor=0xFF6600&BarPosition=1"

表示影片地址是"http://www.transformersmovie.com/transformers_640.flv",标题是"变形金刚预告片",控制栏颜色是0xFF6600,控制栏位置在下方

<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0" width="500" height="224">
<param name="movie" value="http://www.ruochi.com/product/vcastr2/vcastr22.swf">
<param name="quality" value="high">
<param name="allowFullScreen" value="true" />
<param name="FlashVars" value="vcastr_file=http://www.transformersmovie.com/transformers_640.flv&vcastr_title=变形金刚预告片&BarColor=0xFF6600&BarPosition=1" />
<embed src="http://www.ruochi.com/product/vcastr2/vcastr22.swf" allowFullScreen="true" FlashVars="vcastr_file=http://www.transformersmovie.com/transformers_640.flv&vcastr_title=变形金刚预告片&BarColor=0xFF6600&BarPosition=1" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="500" height="224"></embed>
</object>

参数名称
 参数说明 默认值
vcastr_file 方法2传递影片flv文件地址参数,多个使用|分开 空
vcastr_title 影片标题参数,多个使用|分开,与方法2配合使用 空
vcastr_xml 方法3 传递影片flv文件地址参数,样板参考 http://www.ruochi.com/product/vcastr2/vcastr.xml  vcastr.xml
IsAutoPlay 影片自动播放参数:0表示不自动播放,1表示自动播放 0
IsContinue 影片连续播放参数:0表示不连续播放,1表示连续循环播 1
IsRandom 影片随机播放参数:0表示不随机播放,1表示随机播放 0
DefaultVolume 默认音量参数 :0-100 的数值,设置影片开始默认音量大小 100
BarPosition 控制栏位置参数 :0表示在影片上浮动显示,1表示在影片下方显示 0
IsShowBar 控制栏显示参数 :0表示不显示;1表示一直显示;2表示鼠标悬停时显示;3表示开始不显示,鼠标悬停后显示 2
BarColor 播放控制栏颜色,颜色都以0x开始16进制数字表示 0x000033
BarTransparent 播放控制栏透明度 60
GlowColor 按键图标颜色,颜色都以0x开始16进制数字表示 0x66ff00
IconColor 鼠标悬停时光晕颜色,颜色都以0x开始16进制数字表示 0xFFFFFF
TextColor 播放器文字颜色,颜色都以0x开始16进制数字表示 0xFFFFFF
LogoText 可以添加自己网站名称等信息(英文) 空
LogoUrl 可以从外部读取logo图片,注意自己调整logo大小,支持图片格式和swf格式 空
EndSwf 影片播放结束后,从外部读取swf文件,可以添加相关影片信息,影片分享等信息,需自己制作 空
BeginSwf 影片开始播放之前,从外部读取swf文件,可以添加广告,或者网站信息,需自己制作 空
IsShowTime 是否显示时间 : 0表示不显示时间,1表示显示时间 1
BufferTime 影片缓冲时间,单位(秒) 2


常见问题

问:Logo 文字无法显示
答:Logo 文字不能支持中文,可以用LogoUrl参数将Logo做成.swf文件或者.png文件。

问:xml 如何设置高级参数
答:如下

<param name="FlashVars" value="vcastr_xml=http://www.ruochi.com/product/vcastr2/vcastr.xml&vcastr_title=幸福的脚丫预告片|变形金刚预告片|江南MV|魔兽世界-晚安部落&BarColor=0xFF6600&BarPosition=1" />
<embed src="http://www.ruochi.com/product/vcastr2/vcastr2.swf" allowFullScreen="true" FlashVars="vcastr_xml=http://www.ruochi.com/product/vcastr2/vcastr.xml&vcastr_title=幸福的脚丫预告片|变形金刚预告片|江南MV|魔兽世界-晚安部落&BarColor=0xFF6600&BarPosition=1"


问:不能全屏
答:需要升级到flashplayer9.0以上

问:不能退出全屏
答:双击可以进入或退出全屏

问:影片不能拖动进度
答:是由于转换文件格式时候有一些信息丢失,可以使用FLV MetaData Injector修复, 载地址: http://www.buraks.com/flvmdi ;

问:flv放在自己服务器上就不能播放了
答:是由于您的服务器不支持.flv文件格式下载,修改成其他格式比如.swf,当然,相应的vcastr_file或者vcastr_xml中的flv文件名也要修改成.swf

服务
提供付费定制或者修改播放器服务

使用条款:
本软件完全免费,甚至可用作商业用途。
但不可对本软件进行反编译,修改和再次分发。
提供付费的个性化修改服务


有任何建议,可以发到:
http://www.ruochi.com/main/post/24.html
或者ruochi_com@163.com

Created By Ruochi.com
http://www.Ruochi.com
2007-1-1

- 作者: chang110cn 2008年03月20日, 星期四 15:14  回复(0) |  引用(0) 加入博采

利用GOOGLE的FLV播放器在线播放FLV文件的代码

首先知道Google播放器的地址:

http://video.google.com/googleplayer.swf


然后找到 flv文件的地址,例如:

http://v1.ouou.com/BAB51A4D332E42A1/_01/data/video_source/videos/oubj/2007/02/01/1170295437055.flv

然后找到你想要在开始播放前显示的缩略图例如:

http://www.eooeo.com/IMAGES1/top2.jpg

最终形成两种代码:

有缩略图点击播放:

http://video.google.com/googleplayer.swf?videoUrl=http://music1.hexun.com/Save/Video/2006/1206/126/M_7E83044DFF2983F3.FLV&thumbnailUrl=http://www.eooeo.com/IMAGES1/top2.jpg&playerMode=normal" type="application/x-shockwave-flash" wmode="transparent" quality="high" width="450" height="370" autostart="true">

有缩略图自动播放:
http://video.google.com/googleplayer.swf?videoUrl=http://music1.hexun.com/Save/Video/2006/1206/126/M_7E83044DFF2983F3.FLV&thumbnailUrl=http://www.eooeo.com/IMAGES1/top2.jpg&playerMode=normal&autoPlay=true" type="application/x-shockwave-flash" wmode="transparent" quality="high" width="450" height="370" autostart="true">

缩率图也可以不要:
http://video.google.com/googleplayer.swf?videoUrl=http://music1.hexun.com/Save/Video/2006/1206/126/M_7E83044DFF2983F3.FLV" type="application/x-shockwave-flash" wmode="transparent" quality="high" width="450" height="370" autostart="true">
http://video.google.com/googleplayer.swf?videoUrl=http://v1.ouou.com/BAB51A4D332E42A1/_01/data/video_source/videos/oubj/2007/02/01/1170295437055.flv

OK啦

- 作者: chang110cn 2008年03月20日, 星期四 15:12  回复(0) |  引用(0) 加入博采

用js实现广告样式的图片滚动

一个网友给的,用起来挺方便.

<html>
 <head>
  <title>WebForm1</title>
  <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
  <meta name="CODE_LANGUAGE" Content="C#">
  <meta name="vs_defaultClientScript" content="JavaScript">
  <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
  <style type="text/css">
 #castroom { OVERFLOW: hidden; WIDTH: 730px; POSITION: relative; HEIGHT: 88px; } 
</style>
  <script language="javascript">    
 
 /*************用户设定*****************/
 
 var scrollPerRowTime = 6000;    //滚动一行所用时长
 var movePerPixTime = 15;  //移动一个象素时长  
 
 var tableID="table_AD";   //要滚动的表格ID
 var rowHeight=88;    //表格高度 
 
 /************************************/
 
 
 var curShowRowIndex=0;   //当前显示行号 
 var oTable=null;
 var onMouseOver=false;
   
 //开始滚动
 function StartScroll()
 {
  initTable(); 
  window.setInterval("startShow()",scrollPerRowTime);            
 }
 
 //初始化表格,设置定位方式,隐藏表格
 function initTable()
 {
  oTable=window.document.getElementById(tableID);    
  oTable.style.position="relative";    //设置为关联定位方式
      
  for(var i=0;i<oTable.rows.length;i++) 
  {    
   oTable.rows[i].style.height = rowHeight; 
  }
  oTable.style.top=0;
  var oDiv=window.document.getElementById("castroom");
  
  if(oDiv!=null)
  {
   oDiv.onmouseover=DivOnMouseOver;
   oDiv.onmouseout=DivOnMouseOut;
   //oDiv.onmouseout={ onMouseOver=false};
  }            
 }
 
 function DivOnMouseOver()
 {
  onMouseOver=true;
 }
 
 function DivOnMouseOut()
 {
  onMouseOver=false;
 }    
 
 //完成滚动一行         
 function startShow()
 {   
 
  if(!onMouseOver)
  {
   //0.5秒开始移动
   window.setTimeout("moveRow()",1500);    
  
   //循环改变当前显示行号          
   curShowRowIndex = curShowRowIndex<(oTable.rows.length-1) ? curShowRowIndex+1:0;
  }           
 }
 
 
 //移动一行
 function moveRow()
 { 
  if(curShowRowIndex==0)
  {
   oTable.style.top=rowHeight;
  }      
  //开始移动            
  window.setTimeout("moveOnePix("+ rowHeight +")",movePerPixTime);   
 }   
 
 
 //移动一个单位 temp为移动后所剩高度
 function moveOnePix(tempHeight)
 {     
  if(tempHeight>0 )  //继续移动 
  {   
   if(!onMouseOver)
   {       
    tempHeight--; 
   
    var tempTop=oTable.style.top;
    tempTop=tempTop.replace("px","");      
    oTable.style.top =Number(tempTop) - 1;
   }
   window.setTimeout("moveOnePix("+ tempHeight +")",movePerPixTime);
  }        
 }     
</script>
  <table align="center" width="316" border="0">
   <tr>
    <td><DIV id="castroom">
      <table id="table_AD" width="100%" border="0" cellspacing="0" cellpadding="0">
       <tr>
        <td><table width="100%" border="0" cellspacing="0" cellpadding="0">
          <tr>
           <td class="td3"><img border="0" src="/Web.Booking_Internet/Images/PanGolf/Ad/ad%20(3).jpg" width="170"
             height="66" /></td>
           <td class="td3"><img border="0" src="/Web.Booking_Internet/Images/PanGolf/Ad/ad%20(4).jpg" width="170"
             height="66" /></td>
           <td class="td3"><img border="0" src="/Web.Booking_Internet/Images/PanGolf/Ad/ad%20(5).jpg" width="170"
             height="66" /></td>
           <td class="td4"><img border="0" src="/Web.Booking_Internet/Images/PanGolf/Ad/ad.jpg" width="170" height="66" /></td>
          </tr>
          <tr>
           <td class="td3"><p align="center"><font face="Arial">G-AXE GOLF CO.,LTD.</font></p>
           </td>
           <td class="td3"><p align="center">唯尔胜体育用品</p>
           </td>
           <td class="td3"><p align="center">九龙山高尔夫球会</p>
           </td>
           <td class="td4"><p align="center">中国高尔夫高球假期</p>
           </td>
          </tr>
         </table>
        </td>
       </tr>
       <tr>
        <td><table width="100%" border="0" cellspacing="0" cellpadding="0">
          <tr>
           <td class="td3"><img border="0" src="/Web.Booking_Internet/Images/PanGolf/Ad/ad(12).jpg" width="170"
             height="66" /></td>
           <td class="td3"><img border="0" src="/Web.Booking_Internet/Images/PanGolf/Ad/ad%20(9).jpg" width="170"
             height="66" /></td>
           <td class="td3"><img border="0" src="/Web.Booking_Internet/Images/PanGolf/Ad/ad%20(2).jpg" width="170"
             height="66" /></td>
           <td class="td4"><img border="0" src="/Web.Booking_Internet/Images/PanGolf/Ad/ad%20(8).jpg" width="170"
             height="66" /></td>
          </tr>
          <tr>
           <td class="td3"><p align="center"><font face="Arial">PRIMUS GOLF</font></p>
           </td>
           <td class="td3"><p align="center">中信银行</p>
           </td>
           <td class="td3"><p align="center">华夏萄园B区干红</p>
           </td>
           <td class="td4"><p align="center">永衡碱性等离子水</p>
           </td>
          </tr>
         </table>
        </td>
       </tr>
       <tr>
        <td><table width="100%" border="0" cellspacing="0" cellpadding="0">
          <tr>
           <td class="td3"><img border="0" src="/Web.Booking_Internet/Images/PanGolf/Ad/ad%20(7).jpg" width="170"
             height="66" /></td>
           <td class="td3"><img border="0" src="/Web.Booking_Internet/Images/PanGolf/Ad/ad(11).jpg" width="170"
             height="66" /></td>
           <td class="td3"><img border="0" src="/Web.Booking_Internet/Images/PanGolf/Ad/ad%20(6).jpg" width="170"
             height="66" /></td>
           <td class="td4"><img border="0" src="/Web.Booking_Internet/Images/PanGolf/Ad/ad%20(10).jpg" width="170"
             height="66" /></td>
          </tr>
          <tr>
           <td class="td3"><p align="center">聚成企业培训</p>
           </td>
           <td class="td3"><p align="center">威龙干红葡萄酒</p>
           </td>
           <td class="td3"><p align="center">肇庆高尔夫渡假村</p>
           </td>
           <td class="td4"><p align="center">豪麟名鞋世家</p>
           </td>
          </tr>
         </table>
        </td>
       </tr>
      </table>
     </DIV>
    </td>
   </tr>
  </table>
  <script language="javascript">
 StartScroll();  
</script>
 </head>
 <body MS_POSITIONING="GridLayout">
  <form id="Form1" method="post" runat="server">
  </form>
 </body>
</html>

- 作者: chang110cn 2007年01月26日, 星期五 09:03  回复(1) |  引用(0) 加入博采

用js实现力图片新闻式的幻灯片变化

<HTML>
 <HEAD>
  <title>test</title>
  <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
  <meta name="CODE_LANGUAGE" Content="C#">
  <meta name="vs_defaultClientScript" content="JavaScript">
  <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
  <style> #g_div{text-align:right;overflow:hidden}
 .b{width:24px; height:16px; background:#737373; font-size:14px; font-weight:bold; color:#fff; text-decoration:none;margin-left:1px}
 .b:hover{width:24px; height:16px; background:#780001; font-size:14px; font-weight:bold; color:#fff; text-decoration:none;margin-left:1px}
 .bhover{width:24px; height:16px; background:#780001; font-size:14px; font-weight:bold; color:#fff; text-decoration:none;margin-left:1px}
  </style>
 </HEAD>
 <BODY>
  <P><FONT face="宋体"></FONT>&nbsp;</P>
  <FONT face="宋体"></FONT>
  <div id="g_div" style="WIDTH:270px;HEIGHT:252px">
  <a href="#" target="_blank"><img id="g_img" style="BORDER-RIGHT:green 1px solid; BORDER-TOP:green 1px solid; FILTER:revealTrans(duration=1,transition=23); BORDER-LEFT:green 1px solid; WIDTH:266px; BORDER-BOTTOM:green 1px solid; HEIGHT:220px" src="http://zi.csdn.net/xian.gif"> </a><a href="http://www.baidu.com/" for="http://zi.csdn.net/xian.gif" target="_blank">
  1.CSDN程序员</a><a href="http://www.126.com/" for="http://zi.csdn.net/xian.gif" target="_blank">2.CSDN程序员</a><a href="http://mp3.baidu.com/" for="http://zi.csdn.net/xian.gif" target="_blank">3.CSDN程序员</a><a href="http://post.baidu.com/" for="http://zi.csdn.net/new-mba.gif" target="_blank">4.CSDN程序员</a><a href="http://top.baidu.com/" for="http://zi.csdn.net/book.jpg" target="_blank">5.CSDN程序员</a>
  </div>
  <form id="Form1" method="post" runat="server">
  </form>
 </BODY>
</HTML>

  <script language="JavaScript">
function f(){
var g_sec=5          //几秒后切换图片
var g_items=new Array()
var g_div=document.getElementById("g_div")
var g_img=document.getElementById("g_img")
var g_imglink=g_img.parentElement
var arr=g_div.getElementsByTagName("A")
var arr_length=arr.length
var g_index=1

var show_img=function(n){ 
   if (/\d+/.test(n)){
var prev=g_index+1
g_index=n-1
   }else{  
var prev=(g_index>arr.length)?(arr_length-1):g_index+1
g_index=(g_index<arr_length-2)?(++g_index):0
   }
   if (document.all){
   g_img.filters.revealTrans.Transition=23;
  g_img.filters.revealTrans.apply();
  g_img.filters.revealTrans.play();
    }
 arr[prev].className="b" 
 arr[g_index+1].className="bhover"
 g_img.src=g_items[g_index].img.src
 g_img.title=g_items[g_index].txt
 g_imglink.href=g_items[g_index].url 
 g_imglink.target=g_items[g_index].target
 
}

for(var i=1;i<arr_length;i++){
g_items.push({txt:arr[i].innerHTML,
url:arr[i].href,
target:arr[i].target,
img:(function(){var o=new Image;o.src=arr[i].getAttribute("for");return o})()})
arr[i].title=arr[i].innerHTML
arr[i].innerHTML=[i,"&nbsp;"].join("")
arr[i].className="b"
arr[i].onclick=function(){
event.returnValue=false;
show_img(event.srcElement.innerText)
}
}
show_img(1)
var t=window.setInterval(show_img,g_sec*1000)
g_img.onmouseover=function(){window.clearInterval(t)}
g_img.onmouseout=function(){t=window.setInterval(show_img,g_sec*1000)} 
}

window.attachEvent("onload",f)
  </script>

- 作者: chang110cn 2007年01月26日, 星期五 08:58  回复(0) |  引用(0) 加入博采

主窗体和子窗体之间如何相互操作对方的控件(转)

很多人都苦恼于如何在子窗体中操作主窗体上的控件,或者在主窗体中操作子窗体上的控件。相比较而言,后面稍微简单一些,只要在主窗体中创建子窗体的时候,保留所创建子窗体对象即可。

 

下面重点介绍前一种,目前常见的有两种方法,基本上大同小异:

第一种,在主窗体类中定义一个静态成员,来保存当前主窗体对象,例如:

        public static yourMainWindow pCurrentWin = null;

 

       然后在主窗体构造函数中,给静态成员初始化,如下:

            pCurrentWin = this;

 

       那么在子窗体中调用父窗体,可以通过“主窗体类名. pCurrentWin”来操作当前的主窗体。

 

       第二种,是在子窗体中定义一个私有成员,来保存当前主窗体对象,例如:

        private yourMainWindow pParentWin = null;

      

       然后在子窗体构造函数中,加一参数,如下:

        public yourChildWindow( yourMainWindow WinMain )

        {

            pParentWin = WinMain;

            //Other code

}

      

       在主窗体创建子窗体的时候,要把this作为参数来构造子窗体,这样在子窗体中调用父窗体,可以直接用“this.pParentWin”就可以了

 

       不过以上所作的,只是让你能够访问当前主窗体对象,那么如何操作控件,很多人直接修改控件的成员访问符,即把“private”改为“public”,我觉得这样破坏了本身类的封装,所以我比较喜欢的做法是增加公有属性或方法来供调用,例如:

        public string ButtonText

        {

            get{ return btn.Text;}

            set{ btn.Text = value;}

        }

 

        public void Button_Click()

        {

            this.btnDConvert.PerformClick();//Execute button click

        }

      

      



Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=628285

- 作者: chang110cn 2006年09月12日, 星期二 17:43  回复(1) |  引用(0) 加入博采

ftp下载文件通用类

FTP服务器很容易建,如何用C#上传下载文件呢.网上找了个通用的类.希望对大家有帮助.

ftplib.cs


using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;

namespace FTPLib
{
 public class FTP
 {
  #region Public Variables

  ///


  /// IP address or hostname to connect to
  ///

  public string server;
  ///
  /// Username to login as
  ///

  public string user;
  ///
  /// Password for account
  ///

  public string pass;
  ///
  /// Port number the FTP server is listening on
  ///

  public int port;
  ///
  /// The timeout (miliseconds) for waiting on data to arrive
  ///

  public int timeout;
  
  #endregion

  #region Private Variables
  
  private string messages; // server messages
  private string responseStr; // server response if the user wants it.
  private bool passive_mode;  // #######################################
  private long bytes_total; // upload/download info if the user wants it.
  private long file_size; // gets set when an upload or download takes place
  private Socket main_sock;
  private IPEndPoint main_ipEndPoint;
  private Socket listening_sock;
  private Socket data_sock;
  private IPEndPoint data_ipEndPoint;
  private FileStream file;
  private int response;
  private string bucket;
  
  #endregion
  
  #region Constructors
  ///


  /// Constructor
  ///

  public FTP()
  {
   server = null;
   user = null;
   pass = null;
   port = 21;
   passive_mode = true;  // #######################################
   main_sock = null;
   main_ipEndPoint = null;
   listening_sock = null;
   data_sock = null;
   data_ipEndPoint = null;
   file = null;
   bucket = "";
   bytes_total = 0;
   timeout = 10000; // 10 seconds
   messages = "";
  }
  ///
  /// Constructor
  ///

  /// Server to connect to
  /// Account to login as
  /// Account password
  public FTP(string server, string user, string pass)
  {
   this.server = server;
   this.user = user;
   this.pass = pass;
   port = 21;
   passive_mode = true;  // #######################################
   main_sock = null;
   main_ipEndPoint = null;
   listening_sock = null;
   data_sock = null;
   data_ipEndPoint = null;
   file = null;
   bucket = "";
   bytes_total = 0;
   timeout = 10000; // 10 seconds
   messages = "";
  }
  ///
  /// Constructor
  ///

  /// Server to connect to
  /// Port server is listening on
  /// Account to login as
  /// Account password
  public FTP(string server, int port, string user, string pass)
  {
   this.server = server;
   this.user = user;
   this.pass = pass;
   this.port = port;
   passive_mode = true;  // #######################################
   main_sock = null;
   main_ipEndPoint = null;
   listening_sock = null;
   data_sock = null;
   data_ipEndPoint = null;
   file = null;
   bucket = "";
   bytes_total = 0;
   timeout = 10000; // 10 seconds
   messages = "";
  }

  #endregion

  ///


  /// Connection status to the server
  ///

  public bool IsConnected
  {
   get
   {
    if (main_sock != null)
     return main_sock.Connected;
    return false;
   }
  }
  ///
  /// Returns true if the message buffer has data in it
  ///

  public bool MessagesAvailable
  {
   get
   {
    if(messages.Length > 0)
     return true;
    return false;
   }
  }
  ///
  /// Server messages if any, buffer is cleared after you access this property
  ///

  public string Messages
  {
   get
   {
    string tmp = messages;
    messages = "";
    return tmp;
   }
  }
  ///
  /// The response string from the last issued command
  ///

  public string ResponseString
  {
   get
   {
    return responseStr;
   }
  }
  ///
  /// The total number of bytes sent/recieved in a transfer
  ///

  public long BytesTotal  // #######################################
  {
   get
   {
    return bytes_total;
   }
  }
  ///
  /// The size of the file being downloaded/uploaded (Can possibly be 0 if no size is available)
  ///

  public long FileSize  // #######################################
  {
   get
   {
    return file_size;
   }
  }
  ///
  /// True:  Passive mode [default]
  /// False: Active Mode
  ///

  public bool PassiveMode  // #######################################
  {
   get
   {
    return passive_mode;
   }
   set
   {
    passive_mode = value;
   }
  }


  private void Fail()
  {
   Disconnect();
   throw new Exception(responseStr);
  }


  private void SetBinaryMode(bool mode)
  {
   if (mode)
    SendCommand("TYPE I");
   else
    SendCommand("TYPE A");

   ReadResponse();
   if (response != 200)
    Fail();
  }


  private void SendCommand(string command)
  {
   Byte[] cmd = Encoding.ASCII.GetBytes((command + "\r\n").ToCharArray());

#if (FTP_DEBUG)
   if (command.Length > 3 && command.Substring(0, 4) == "PASS")
    Console.WriteLine("\rPASS xxx");
   else
    Console.WriteLine("\r" + command);
#endif

   main_sock.Send(cmd, cmd.Length, 0);
  }


  private void FillBucket()
  {
   Byte[] bytes = new Byte[512];
   long bytesgot;
   int msecs_passed = 0;  // #######################################

   while(main_sock.Available < 1)
   {
    System.Threading.Thread.Sleep(50);
    msecs_passed += 50;
    // this code is just a fail safe option
    // so the code doesn't hang if there is
    // no data comming.
    if (msecs_passed > timeout)
    {
     Disconnect();
     throw new Exception("Timed out waiting on server to respond."); 
    }
   }

   while(main_sock.Available > 0)
   {
    bytesgot = main_sock.Receive(bytes, 512, 0);
    bucket += Encoding.ASCII.GetString(bytes, 0, (int)bytesgot);
    // this may not be needed, gives any more data that hasn't arrived
    // just yet a small chance to get there.
    System.Threading.Thread.Sleep(50);
   }
  }


  private string GetLineFromBucket()
  {
   int i;
   string buf = "";

   if ((i = bucket.IndexOf('\n')) < 0)
   {
    while(i < 0)
    {
     FillBucket();
     i = bucket.IndexOf('\n');
    }
   }

   buf = bucket.Substring(0, i);
   bucket = bucket.Substring(i + 1);

   return buf;
  }


  // Any time a command is sent, use ReadResponse() to get the response
  // from the server. The variable responseStr holds the entire string and
  // the variable response holds the response number.
  private void ReadResponse()
  {
   string buf;
   messages = "";

   while(true)
   {
    //buf = GetLineFromBucket();
    buf = GetLineFromBucket();

#if (FTP_DEBUG)
    Console.WriteLine(buf);
#endif
    // the server will respond with "000-Foo bar" on multi line responses
    // "000 Foo bar" would be the last line it sent for that response.
    // Better example:
    // "000-This is a multiline response"
    // "000-Foo bar"
    // "000 This is the end of the response"
    if (Regex.Match(buf, "^[0-9]+ ").Success)
    {
     responseStr = buf;
     response = int.Parse(buf.Substring(0, 3));
     break;
    }
    else
     messages += Regex.Replace(buf, "^[0-9]+-", "") + "\n";
   }
  }


  // if you add code that needs a data socket, i.e. a PASV or PORT command required,
  // call this function to do the dirty work. It sends the PASV or PORT command,
  // parses out the port and ip info and opens the appropriate data socket
  // for you. The socket variable is private Socket data_socket. Once you
  // are done with it, be sure to call CloseDataSocket()
  private void OpenDataSocket()
  {
   if (passive_mode)  // #######################################
   {
    string[] pasv;
    string server;
    int port;

    Connect();
    SendCommand("PASV");
    ReadResponse();
    if (response != 227)
     Fail();

    try
    {
     int i1, i2;

     i1 = responseStr.IndexOf('(') + 1;
     i2 = responseStr.IndexOf(')') - i1;
     pasv = responseStr.Substring(i1, i2).Split(',');
    }
    catch(Exception)
    {
     Disconnect();
     throw new Exception("Malformed PASV response: " + responseStr);
    }

    if (pasv.Length < 6)
    {
     Disconnect();
     throw new Exception("Malformed PASV response: " + responseStr);
    }

    server = String.Format("{0}.{1}.{2}.{3}", pasv[0], pasv[1], pasv[2], pasv[3]);
    port = (int.Parse(pasv[4]) << 8) + int.Parse(pasv[5]);

    try
    {
#if (FTP_DEBUG)
     Console.WriteLine("Data socket: {0}:{1}", server, port);
#endif
     CloseDataSocket();
     
#if (FTP_DEBUG)
     Console.WriteLine("Creating socket...");
#endif
     data_sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     
#if (FTP_DEBUG)
     Console.WriteLine("Resolving host");
#endif

     data_ipEndPoint = new IPEndPoint(Dns.GetHostByName(server).AddressList[0], port);

     
#if (FTP_DEBUG)
     Console.WriteLine("Connecting..");
#endif
     data_sock.Connect(data_ipEndPoint);

#if (FTP_DEBUG)
     Console.WriteLine("Connected.");
#endif
    }
    catch(Exception ex)
    {
     throw new Exception("Failed to connect for data transfer: " + ex.Message);
    }
   }
   else  // #######################################
   {
    Connect();

    try
    {
#if (FTP_DEBUG)
     Console.WriteLine("Data socket (active mode)");
#endif
     CloseDataSocket();
     
#if (FTP_DEBUG)
     Console.WriteLine("Creating listening socket...");
#endif
     listening_sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

#if (FTP_DEBUG)
     Console.WriteLine("Binding it to local address/port");
#endif
     // for the PORT command we need to send our IP address; let's extract it
     // from the LocalEndPoint of the main socket, that's already connected
     string sLocAddr = main_sock.LocalEndPoint.ToString();
     int ix = sLocAddr.IndexOf(':');
     if (ix < 0)
     {
      throw new Exception("Failed to parse the local address: " + sLocAddr);
     }
     string sIPAddr = sLocAddr.Substring(0, ix);
     // let the system automatically assign a port number (setting port = 0)
     System.Net.IPEndPoint localEP = new IPEndPoint(IPAddress.Parse(sIPAddr), 0);

     listening_sock.Bind(localEP);
     sLocAddr = listening_sock.LocalEndPoint.ToString();
     ix = sLocAddr.IndexOf(':');
     if (ix < 0)
     {
      throw new Exception("Failed to parse the local address: " + sLocAddr);
     }
     int nPort = int.Parse(sLocAddr.Substring(ix + 1));
#if (FTP_DEBUG)
     Console.WriteLine("Listening on {0}:{1}", sIPAddr, nPort);
#endif
     // start to listen for a connection request from the host (note that
     // Listen is not blocking) and send the PORT command
     listening_sock.Listen(1);
     string sPortCmd = string.Format("PORT {0},{1},{2}",
             sIPAddr.Replace('.', ','),
             nPort / 256, nPort % 256);
     SendCommand(sPortCmd);
     ReadResponse();
     if (response != 200)
      Fail();
    }
    catch(Exception ex)
    {
     throw new Exception("Failed to connect for data transfer: " + ex.Message);
    }
   }
  }


  private void ConnectDataSocket()  // #######################################
  {
   if (data_sock != null)  // already connected (always so if passive mode)
    return;

   try
   {
#if (FTP_DEBUG)
    Console.WriteLine("Accepting the data connection.");
#endif
    data_sock = listening_sock.Accept(); // Accept is blocking
    listening_sock.Close();
    listening_sock = null;

    if (data_sock == null)
    {
     throw new Exception("Winsock error: " +
      Convert.ToString(System.Runtime.InteropServices.Marshal.GetLastWin32Error()) );
    }
#if (FTP_DEBUG)
    Console.WriteLine("Connected.");
#endif
   }
   catch(Exception ex)
   {
    throw new Exception("Failed to connect for data transfer: " + ex.Message);
   }
  }


  private void CloseDataSocket()
  {
#if (FTP_DEBUG)
   Console.WriteLine("Attempting to close data channel socket...");
#endif
   if (data_sock != null)
   {
    if (data_sock.Connected)
    {
#if (FTP_DEBUG)
      Console.WriteLine("Closing data channel socket!");
#endif 
      data_sock.Close();
#if (FTP_DEBUG)
      Console.WriteLine("Data channel socket closed!");
#endif
    }
    data_sock = null;
   }

   data_ipEndPoint = null;
  }
  ///


  /// Closes all connections to the ftp server
  ///

  public void Disconnect()
  {
   CloseDataSocket();

   if (main_sock != null)
   {
    if (main_sock.Connected)
    {
     SendCommand("QUIT");
     main_sock.Close();
    }
    main_sock = null;
   }

   if (file != null)
    file.Close();

   main_ipEndPoint = null;
   file = null;
  }
  ///


  /// Connect to a ftp server
  ///

  /// IP or hostname of the server to connect to
  /// Port number the server is listening on
  /// Account name to login as
  /// Password for the account specified
  public void Connect(string server, int port, string user, string pass)
  {
   this.server = server;
   this.user = user;
   this.pass = pass;
   this.port = port;

   Connect();
  }
  ///


  /// Connect to a ftp server
  ///

  /// IP or hostname of the server to connect to
  /// Account name to login as
  /// Password for the account specified
  public void Connect(string server, string user, string pass)
  {
   this.server = server;
   this.user = user;
   this.pass = pass;

   Connect();
  }
  ///


  /// Connect to an ftp server
  ///

  public void Connect()
  {
   if (server == null)
    throw new Exception("No server has been set.");
   if (user == null)
    throw new Exception("No username has been set.");

   if (main_sock != null)
    if (main_sock.Connected)
     return;

   main_sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
   main_ipEndPoint = new IPEndPoint(Dns.GetHostByName(server).AddressList[0], port);
   
   try
   {
    main_sock.Connect(main_ipEndPoint); 
   }
   catch(Exception ex)
   {
    throw new Exception(ex.Message);
   }

   ReadResponse();
   if (response != 220)
    Fail();

   SendCommand("USER " + user);
   ReadResponse();

   switch(response)
   {
    case 331:
     if (pass == null)
     {
      Disconnect();
      throw new Exception("No password has been set.");
     }
     SendCommand("PASS " + pass);
     ReadResponse();
     if (response != 230)
      Fail();
     break;
    case 230:
     break;
   }
   
   return;
  }
  ///


  /// Retrieves a list of files from the ftp server
  ///

  /// An ArrayList of files
  public ArrayList List()
  {
   Byte[] bytes = new Byte[512];
   string file_list = "";
   long bytesgot = 0;
   int msecs_passed = 0;
   ArrayList list = new ArrayList();
  
   Connect();
   OpenDataSocket();
   SendCommand("LIST");
   ReadResponse();

   //FILIPE MADUREIRA.
   //Added response 125
   switch(response)
   {
    case 125:
    case 150:
     break;
    default:
     CloseDataSocket();
     throw new Exception(responseStr);
   }
   ConnectDataSocket();  // #######################################

   while(data_sock.Available < 1)
   {
    System.Threading.Thread.Sleep(50);
    msecs_passed += 50;
    // this code is just a fail safe option
    // so the code doesn't hang if there is
    // no data comming.
    if (msecs_passed > (timeout / 10))
    {
     //CloseDataSocket();
     //throw new Exception("Timed out waiting on server to respond.");
     
     //FILIPE MADUREIRA.
     //If there are no files to list it gives timeout.
     //So I wait less time and if no data is received, means that there are no files
     break;//Maybe there are no files
    }
   }

   while(data_sock.Available > 0)
   {
    bytesgot = data_sock.Receive(bytes, bytes.Length, 0);
    file_list += Encoding.ASCII.GetString(bytes, 0, (int)bytesgot);
    System.Threading.Thread.Sleep(50); // *shrug*, sometimes there is data comming but it isn't there yet.
   }
   
   CloseDataSocket();

   ReadResponse();
   if (response != 226)
    throw new Exception(responseStr);

   foreach(string f in file_list.Split('\n'))
   {
    if (f.Length > 0 && !Regex.Match(f, "^total").Success)
     list.Add(f.Substring(0, f.Length - 1));
   }

   return list;
  }
  ///


  /// Gets a file list only
  ///

  /// ArrayList of files only
  public ArrayList ListFiles()
  {
   ArrayList list = new ArrayList();

   foreach(string f in List())
   {
    //FILIPE MADUREIRA
    //In Windows servers it is identified by


    if ((f.Length > 0))
    {
     if ((f[0] != 'd') && (f.ToUpper().IndexOf("") < 0))
      list.Add(f);
    }
   }

   return list;
  }
  ///


  /// Gets a directory list only
  ///

  /// ArrayList of directories only
  public ArrayList ListDirectories()
  {
   ArrayList list = new ArrayList();

   foreach(string f in List())
   {
    //FILIPE MADUREIRA
    //In Windows servers it is identified by


    if (f.Length > 0)
    {
     if ((f[0] == 'd') || (f.ToUpper().IndexOf("") >= 0))
      list.Add(f);
    }
   }

   return list;
  }
  ///


  /// Returns the 'Raw' DateInformation in ftp format. (YYYYMMDDhhmmss). Use GetFileDate to return a DateTime object as a better option.
  ///

  /// Remote FileName to Query
  /// Returns the 'Raw' DateInformation in ftp format
  public string GetFileDateRaw(string fileName)
  {
   Connect();
   
   SendCommand("MDTM " + fileName);
   ReadResponse();
   if(response != 213)
   {
#if (FTP_DEBUG)
    Console.Write("\r" + responseStr);
#endif
    throw new Exception(responseStr);
   }
   
   return (this.responseStr.Substring(4));
  }
  ///
  /// GetFileDate will query the ftp server for the date of the remote file.
  ///

  /// Remote FileName to Query
  /// DateTime of the Input FileName
  public DateTime GetFileDate(string fileName)
  {
   return ConvertFTPDateToDateTime(GetFileDateRaw(fileName));
  }

  private DateTime ConvertFTPDateToDateTime(string input)
  {
   if(input.Length < 14)
    throw new ArgumentException("Input Value for ConvertFTPDateToDateTime method was too short.");
   
   //YYYYMMDDhhmmss":
   int year = Convert.ToInt16(input.Substring(0,4));
   int month = Convert.ToInt16(input.Substring(4,2));
   int day = Convert.ToInt16(input.Substring(6,2));
   int hour = Convert.ToInt16(input.Substring(8,2));
   int min = Convert.ToInt16(input.Substring(10,2));
   int sec = Convert.ToInt16(input.Substring(12,2));

   return new DateTime(year, month, day, hour, min, sec);
  }
  ///


  /// Get the working directory on the ftp server
  ///

  /// The working directory
  public string GetWorkingDirectory()
  {
   //PWD - print working directory
   Connect();
   SendCommand("PWD");
   ReadResponse();

   if(response != 257)
    throw new Exception(responseStr);
   
   string pwd;
   try
   {
    pwd = responseStr.Substring(responseStr.IndexOf("\"", 0) + 1);//5);
    pwd = pwd.Substring(0, pwd.LastIndexOf("\""));
    pwd = pwd.Replace("\"\"", "\""); // directories with quotes in the name come out as "" from the server
   }
   catch(Exception ex)
   {
    throw new Exception("Uhandled PWD response: " + ex.Message);
   }

   return pwd;
  }
  ///


  /// Change to another directory on the ftp server
  ///

  /// Directory to change to
  public void ChangeDir(string path)
  {
   Connect();
   SendCommand("CWD " + path);
   ReadResponse();
   if (response != 250)
   {
#if (FTP_DEBUG)
    Console.Write("\r" + responseStr);
#endif
    throw new Exception(responseStr);
   }
  }
  ///
  /// Create a directory on the ftp server
  ///

  /// Directory to create
  public void MakeDir(string dir)
  {
   Connect();
   SendCommand("MKD " + dir);
   ReadResponse();
   
   switch(response)
   {
    case 257:
    case 250:
     break;
    default:
#if (FTP_DEBUG)
                    Console.Write("\r" + responseStr);
#endif
     throw new Exception(responseStr);
   }
  }
  ///
  /// Remove a directory from the ftp server
  ///

  /// Name of directory to remove
  public void RemoveDir(string dir)
  {
   Connect();
   SendCommand("RMD " + dir);
   ReadResponse();
   if (response != 250)
   {
#if (FTP_DEBUG)
    Console.Write("\r" + responseStr);
#endif
    throw new Exception(responseStr);
   }
  }
  ///
  /// Remove a file from the ftp server
  ///

  /// Name of the file to delete
  public void RemoveFile(string filename)
  {
   Connect();
   SendCommand("DELE " + filename);
   ReadResponse();
   if (response != 250)
   {
#if (FTP_DEBUG)
    Console.Write("\r" + responseStr);
#endif
    throw new Exception(responseStr);
   }
  }
  ///
  /// Rename a file on the ftp server
  ///

  /// Old file name
  /// New file name
  public void RenameFile(string oldfilename, string newfilename)  // #######################################
  {
   Connect();
   SendCommand("RNFR " + oldfilename);
   ReadResponse();
   if (response != 350)
   {
#if (FTP_DEBUG)
    Console.Write("\r" + responseStr);
#endif
    throw new Exception(responseStr);
   }
   else
   {
    SendCommand("RNTO " + newfilename);
    ReadResponse();
    if (response != 250)
    {
#if (FTP_DEBUG)
     Console.Write("\r" + responseStr);
#endif
     throw new Exception(responseStr);
    }
   }
  }
  ///
  /// Get the size of a file (Provided the ftp server supports it)
  ///

  /// Name of file
  /// The size of the file specified by filename
  public long GetFileSize(string filename)
  {
   Connect();
   SendCommand("SIZE " + filename);
   ReadResponse();
   if (response != 213)
   {
#if (FTP_DEBUG)
    Console.Write("\r" + responseStr);
#endif
    throw new Exception(responseStr);
   }
           
   return Int64.Parse(responseStr.Substring(4));
  }
  ///
  /// Open an upload with no resume if it already exists
  ///

  /// File to upload
  public void OpenUpload(string filename)
  {
   OpenUpload(filename, filename, false);
  }
  ///
  /// Open an upload with no resume if it already exists
  ///

  /// Local file to upload (Can include path to file)
  /// Filename to store file as on ftp server
  public void OpenUpload(string filename, string remotefilename)
  {
   OpenUpload(filename, remotefilename, false);
  }
  ///
  /// Open an upload with resume support
  ///

  /// Local file to upload (Can include path to file)
  /// Attempt resume if exists
  public void OpenUpload(string filename, bool resume)
  {
   OpenUpload(filename, filename, resume);
  }
  ///
  /// Open an upload with resume support
  ///

  /// Local file to upload (Can include path to file)
  /// Filename to store file as on ftp server
  /// Attempt resume if exists
  public void OpenUpload(string filename, string remote_filename, bool resume)
  {
   Connect();
   SetBinaryMode(true);
   OpenDataSocket();

   bytes_total = 0;

   try
   {
    file = new FileStream(filename, FileMode.Open);
   }
   catch(Exception ex)
   {
    file = null;
    throw new Exception(ex.Message);
   }

   file_size = file.Length;

   if (resume)
   {
    long size = GetFileSize(remote_filename);
    SendCommand("REST " + size);
    ReadResponse();
    if (response == 350)
     file.Seek(size, SeekOrigin.Begin);
   }
   
   SendCommand("STOR " + remote_filename);
   ReadResponse();

   switch(response)
   {
    case 125:
    case 150:
     break;
    default:
     file.Close();
     file = null;
     throw new Exception(responseStr);
   }
   ConnectDataSocket();  // ####################################### 

   return;
  }
  ///


  /// Download a file with no resume
  ///

  /// Remote file name
  public void OpenDownload(string filename)
  {
   OpenDownload(filename, filename, false);
  }
  ///
  /// Download a file with optional resume
  ///

  /// Remote file name
  /// Attempt resume if file exists
  public void OpenDownload(string filename, bool resume)
  {
   OpenDownload(filename, filename, resume);
  }
  ///
  /// Download a file with no attempt to resume
  ///

  /// Remote filename
  /// Local filename (Can include path to file)
  public void OpenDownload(string filename, string localfilename)
  {
   OpenDownload(filename, localfilename, false);
  }
  ///
  /// Open a file for download
  ///

  /// The name of the file on the FTP server
  /// The name of the file to save as (Can include path to file)
  /// Attempt resume if file exists
  public void OpenDownload(string remote_filename, string local_filename, bool resume)
  {
   Connect();
   SetBinaryMode(true);

   bytes_total = 0;
   
   try
   {
    file_size = GetFileSize(remote_filename);
   }
   catch
   {
    file_size = 0;
   }
   
   if (resume && File.Exists(local_filename))
   {
    try
    {
     file = new FileStream(local_filename, FileMode.Open);
    }
    catch(Exception ex)
    {
     file = null;
     throw new Exception(ex.Message);
    }

    SendCommand("REST " + file.Length);
    ReadResponse();
    if (response != 350)
     throw new Exception(responseStr);
    file.Seek(file.Length, SeekOrigin.Begin);
    bytes_total = file.Length;
   }
   else
   {
    try
    {
     file = new FileStream(local_filename, FileMode.Create);
    }
    catch(Exception ex)
    {
     file = null;
     throw new Exception(ex.Message);
    }
   }

   OpenDataSocket();
   SendCommand("RETR " + remote_filename);
   ReadResponse();
   
   switch(response)
   {
    case 125:
    case 150:
     break;
    default:
     file.Close();
     file = null;
     throw new Exception(responseStr);
   }
   ConnectDataSocket();  // ####################################### 

   return;
  }
  ///


  /// Upload the file, to be used in a loop until file is completely uploaded
  ///

  /// Bytes sent
  public long DoUpload()
  {
   Byte[] bytes = new Byte[512];
   long bytes_got;

   try
   {
    bytes_got = file.Read(bytes, 0, bytes.Length);
    bytes_total += bytes_got;
    data_sock.Send(bytes, (int)bytes_got, 0);

    if(bytes_got <= 0)
    {
     // the upload is complete or an error occured
     file.Close();
     file = null;
    
     CloseDataSocket();
     ReadResponse();
     switch(response)
     {
      case 226:
      case 250:
       break;
      default:
       throw new Exception(responseStr);
     }
    
     SetBinaryMode(false);
    }
   }
   catch(Exception ex)
   {
    file.Close();
    file = null;
    CloseDataSocket();
    ReadResponse();
    SetBinaryMode(false);
    throw ex;
   }

   return bytes_got;
  }
  ///


  /// Download a file, to be used in a loop until the file is completely downloaded
  ///

  /// Number of bytes recieved
  public long DoDownload()
  {
   Byte[] bytes = new Byte[512];
   long bytes_got;
   
   try
   {
    bytes_got = data_sock.Receive(bytes, bytes.Length, 0);

    if(bytes_got <= 0)
    {
     // the download is done or an error occured
     CloseDataSocket();
     file.Close();
     file = null;
    
     ReadResponse();
     switch(response)
     {
      case 226:
      case 250:
       break;
      default:
       throw new Exception(responseStr);
     }
    
     SetBinaryMode(false);

     return bytes_got;
    }

    file.Write(bytes, 0, (int)bytes_got);
    bytes_total += bytes_got;
   }
   catch(Exception ex)
   {
    CloseDataSocket();
    file.Close();
    file = null;
    ReadResponse();
    SetBinaryMode(false);
    throw ex;
   }

   return bytes_got;
  }
 }
}

//调用这个类实现下载程序

   
   string strFtpIP = ConfigurationSettings.AppSettings["FtpIP"];
   string strUser  = ConfigurationSettings.AppSettings["User"];
   string strPass  = ConfigurationSettings.AppSettings["Pass"];
   string strftpPath = ConfigurationSettings.AppSettings["ftpPath"];
   string[] strftpFile = ConfigurationSettings.AppSettings["ftpFile"].ToString().Split(',');

   // create an instance of the ftp library
   FTPLib.FTP ftplib = new FTPLib.FTP();

   try
   {

    //联接服务器
    ftplib.Connect(strFtpIP,strUser ,strPass);
    

    //    iMax = ftplib.FileSize ;
    for (int i = 0 ;i < strftpFile.Length ; i++)
    {
     
     //下载设置
     ftplib.OpenDownload(strftpFile[i],strftpPath + @"\" + strftpFile[i] );//"Tmri_Wzjl.rar",@"d:\Tmri_Wzjl.rar" );
     while(ftplib.DoDownload() > 0)
     {
      //ftplib.BytesTotal.ToString()  当前进度
      // ftplib.FileSize.ToString()   总长度

      //iNow = ftplib.BytesTotal;

     }
    }

    ftplib.Disconnect();
               
   //    this.Invoke(delDonwload,new object[]{"下载完成!"+System.DateTime.Now.ToString()} );

    
    

   }
   catch(Exception ex)
   {   
    // ex.Message.ToString().Trim();
   // this.Invoke(delDonwload,new object[]{"下载文件出错:"+ex.Message.ToString().Trim()} );
   
      }
  

- 作者: chang110cn 2006年09月8日, 星期五 11:29  回复(0) |  引用(0) 加入博采

用winrar解压缩文件(二)

 用winrar压缩文件(一) 里面说了压缩,现在说解压

   string strDirPath =  ConfigurationSettings.AppSettings["ftpPath"];
   string[] strftpfile =  ConfigurationSettings.AppSettings["ftpFile"].ToString().Trim().Split(',');

   try
   {
    for (int i=0;i    {

     System.Diagnostics.Process Process1=new System.Diagnostics.Process();
     Process1.StartInfo.FileName=@"rar.exe";
     Process1.StartInfo.Arguments=@"x -inul -y -o+ "+ strDirPath + @"\" + strftpfile[i] + "  " + strDirPath;
     Process1.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
     Process1.Start();    //进行解压
   
     while(!Process1.HasExited)          //等待压缩的完成
     {
                    
     }

     Process1.WaitForExit();
     i