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

Upload súboru na FTP server

Zdrojový kód:
using System;
using System.IO;
using System.Net;

...
public static bool FTPUpload(string FTPPath, string FileName, NetworkCredential credentials, bool WithSSL = true)
{
    bool Success = true;
    FileStream FStream = null;
    Stream ReqStream = null;
    try
    {
        FtpWebRequest Request = (FtpWebRequest)WebRequest.Create(FTPPath);
        Request.Method = WebRequestMethods.Ftp.UploadFile;
        Request.EnableSsl = WithSSL;
        Request.Credentials = credentials;
        ReqStream = Request.GetRequestStream();
        FStream = File.OpenRead(FileName);

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

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

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

    return Success;
}
...

Volanie metódy

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

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


Keywords: C#, FTP, Upload

Codeblog