VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > Python基础教程 >
  • C#教程之C# -- FTP上传下载

C# -- FTP上传下载

1. C#实现FTP下载

复制代码
private static void TestFtpDownloadFile(string strFtpPath, string strFileName, string strFtpUser, string strFtpPassWord, string strSaveFileName)
{
    FtpWebRequest ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(strFtpPath + strFileName);
    ftpWebRequest.Credentials = new System.Net.NetworkCredential(strFtpUser, strFtpPassWord);
    ftpWebRequest.UseBinary = true;
    ftpWebRequest.UsePassive = true;
    ftpWebRequest.KeepAlive = true;

    ftpWebRequest.Method = WebRequestMethods.Ftp.DownloadFile;

    FtpWebResponse ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse();
    Stream ftpStream = ftpWebResponse.GetResponseStream();

    FileStream localFileStream = new FileStream(strSaveFileName, FileMode.Create);

    int bufferSize = 1 * 1024 * 1024;

    byte[] byteBuffer = new byte[bufferSize];
    int bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize);
    try
    {
        while (bytesRead > 0)
        {
            localFileStream.Write(byteBuffer, 0, bytesRead);
            bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize);
        }
    }
    catch (Exception ex) { Console.WriteLine(ex.ToString()); }

    localFileStream.Close();
    ftpStream.Close();
    ftpWebResponse.Close();
    ftpWebRequest = null;

    Console.WriteLine("下载完成 ");
}
复制代码

 

2. C#实现FTP上传

复制代码
private static void TestFtpUploadFile(string strFtpPath, string strFileName, string strFtpUser, string strFtpPassWord, string strUploadFileName)
{
    FileInfo uploadFileInfo = new FileInfo(strUploadFileName);
    FtpWebRequest ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(strFtpPath + strFileName);

    ftpWebRequest.UseBinary = true;
    ftpWebRequest.Credentials = new NetworkCredential(strFtpUser, strFtpPassWord);
    ftpWebRequest.KeepAlive = false;
    ftpWebRequest.Method = WebRequestMethods.Ftp.UploadFile;
    ftpWebRequest.ContentLength = uploadFileInfo.Length;

    Stream ftpStream = ftpWebRequest.GetRequestStream();

    FileStream uploadFileReadStream = uploadFileInfo.OpenRead();

    int bufferSize = 1 * 1024 * 1024;

    byte[] byteBuffer = new byte[bufferSize];
    int bytesRead = uploadFileReadStream.Read(byteBuffer, 0, bufferSize);
    try
    {
        while (bytesRead > 0)
        {
            ftpStream.Write(byteBuffer, 0, bytesRead);
            bytesRead = uploadFileReadStream.Read(byteBuffer, 0, bufferSize);
        }
    }
    catch (Exception ex) { Console.WriteLine(ex.ToString()); }

    ftpStream.Close();
    uploadFileReadStream.Close();
    ftpWebRequest = null;

    Console.WriteLine("上传完成 ");
}
复制代码

 


相关教程