当前位置: 首页 > 编程语言 > C#

使用FtpWebRequest下载文件Share

时间:2023-04-10 10:55:13 C#

使用FtpWebRequest下载文件privatevoidDownloadFile(stringuserName,stringpassword,stringftpSourceFilePath,stringlocalDestinationFilePath){intbytesRead=0;字节[]缓冲区=新字节[1024];FtpWebRequest请求=CreateFtpWebRequest(ftpSourceFilePath,用户名,密码,真);request.Method=WebRequestMethods.Ftp.DownloadFile;流阅读器=request.GetResponse().GetResponseStream();BinaryWriterwriter=newBinaryWriter(File.Open(localDestinationFilePath,FileMode.CreateNew));while(true){bytesRead=reader.Read(buffer,0,buffer.Length);如果(bytesRead==0)中断;writer.Write(buffer,0,bytesRead);}}它使用我创建的CreateFtpWebRequest方法:privateFtpWebRequestCreateFtpWebRequest(stringftpDirectoryPath,stringuserName,stringpassword,boolkeepAlive=false){//设置代理为空。在当前配置下,如果未设置此选项,则使用的代理将get来自Web内容网关(防火墙监控系统)的html响应request.Proxy=null;请求.UsePassive=true;请求.UseBinary=true;请求.KeepAlive=keepAlive;request.Credentials=newNetworkCredential(用户名,密码);退货申请;它下载它,但信息总是被破坏。有谁知道发生了什么事?刚弄清楚:privatevoidDownloadFile(stringuserName,stringpassword,stringftpSourceFilePath,stringlocalDestinationFilePath){intbytesRead=0;字节[]缓冲区=新字节[2048];FtpWebRequest请求=CreateFtpWebRequest(ftpSourceFilePath,userNametrue,password,);request.Method=WebRequestMethods.Ftp.DownloadFile;流阅读器=request.GetResponse().GetResponseStream();FileStreamfileStream=newFileStream(localDestinationFilePath,FileMode.Create);while(true){bytesRead=reader.Read(buffer,0,buffer.Length);如果(bytesRead==0)中断;fileStream.Write(buffer,0,bytesRead);}fileStream.Close();不得不使用FileStream。使用.NET框架从FTP服务器下载文件的最简单方法是使用WebClient.DownloadFile方法:WebClientclient=newWebClient();client.Credentials=newNetworkCredential("用户名","密码");client.DownloadFile("ftp://ftp.example.com/remote/path/file.zip",@"C:localpathfile.zip");如果您只需要更大的控件,请使用WebClient类不提供的FtpWebRequest类(如TLS/SSL加密、进度监控等)。一种简单的方法是使用Stream.CopyTo方法将FTP响应流复制到FileStream:FtpWebRequestrequest=(FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip");request.Credentials=newNetworkCredential("用户名","密码");request.Method=WebRequestMethods.Ftp.DownloadFile;使用(StreamftpStream=request.GetResponse().GetResponseStream())使用(StreamfileStream=File.Create(@"C:localpathfile.zip")){ftpStream.CopyTo(fileStream);}只是,如果需要监控下载进度,需要自己复制内容:FtpWebRequestrequest=(FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip");request.Credentials=newNetworkCredential("用户名","密码");request.Method=WebRequestMethods.Ftp.DownloadFile;使用(StreamftpStream=request.GetResponse().GetResponseStream())使用(StreamfileStream=File.Create(@"C:localpathfile.zip")){byte[]buffer=newbyte[10240];诠释阅读;while((read=ftpStream.Read(buffer,0,buffer.Length))>0){fileStream.Write(buff呃,0,读);Console.WriteLine("下载{0}字节",fileStream.Position);}}GUI进度(WinFormsProgressBar)见:FtpWebRequestFTPdownloadwithProgressBar如果你想从远程文件夹下载所有文件,请参考C#通过FTP下载所有文件和子目录。以上就是C#学习教程:使用FtpWebRequest下载文件分享的全部内容。本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: