Táto stránka pre svoju správnu funkčnosť vyžaduje súbory cookies. Slúžia na authentifikáciu návštevníka, analýzu návštevnosti a reklamnú personalizáciu.
logo Knowledge base KB
mobile

Download súboru z FTP servra

Zdrojový kód:

public static bool FTPDownload(string FTPPath, string FileName, NetworkCredential credentials, bool WithSSL = true)
{
    bool Success = true;

    FileStream FStream = null;
    Stream RespStream = null;
    try
    {
        FtpWebRequest Request = (FtpWebRequest)WebRequest.Create(FTPPath);
        Request.Method = WebRequestMethods.Ftp.DownloadFile;
        Request.EnableSsl = WithSSL;
        Request.Credentials = credentials;
        RespStream = Request.GetResponse().GetResponseStream();

        FStream = File.OpenWrite(FileName);

        byte[] Buffer = new byte[4096];
        int BytesCount = 1;
        while (BytesCount != 0)
        {
            BytesCount = RespStream.Read(Buffer, 0, Buffer.Length);

            if (BytesCount > 0)
            {
                FStream.Write(Buffer, 0, BytesCount);
            }
        }
    }
    catch
    {
        Success = false;
    }
    finally
    {
        try
        {
            if (RespStream != null)
                RespStream.Close();
        }
        catch { }

        try
        {
            if (FStream != null)
            {
                FStream.Flush();
                    FStream.Close();
            }
        }
        catch { }
    }

    return Success;
}

Volanie metódy

Zdrojový kód:
string FTPPath = "ftp://server/download/testx.docx";
string FileName = "C:\\temp\\test.docx";

bool OK = FTPDownload(FTPPath, FileName, new NetworkCredential("login", "password"));

Keywords: C#, FTP, Download

Codeblog