其他分享
首页 > 其他分享> > FTP tcpclient 上传文件

FTP tcpclient 上传文件

作者:互联网


var host="localhost";
var port = 21;
var u="username";
var p="password";
var remoteDir = "filesync";
var fp="C:\\Users\\admin\\Desktop\\新建文本文档.txt";


await Upload();


async Task Upload()
{
    var res = "";
    remoteDir = remoteDir.Trim('/');
    var filename = Path.GetFileName(fp);

    TcpClient tcp = new TcpClient();
    tcp.Connect(host, port);
    NetworkStream stream = tcp.GetStream();
    if (tcp.Connected.ToString() != "True")
    {
        Console.WriteLine("Connect Failed!");
        Console.ReadLine();
        return;
    }

    await ReadTcp(stream);
    await cmd(stream, "USER " + u);
    await cmd(stream, "PASS " + p);
    await cmd(stream, "FEAT");
    await cmd(stream, "TYPE I");

    res = await cmd(stream, "CWD /" + remoteDir);
    if (res.StartsWith("550 ")) await cmd(stream, "MKD /" + remoteDir);
    await cmd(stream, "CWD /" + remoteDir);

    res = await cmd(stream, "PASV");
    var commands = res.Split(',');
    if (commands.Length > 4)
    {
        int port2 = int.Parse(commands[4]) * 256 + int.Parse(commands[5].Trim('\r', '\n', ')', '('));
        TcpClient tcpup = new TcpClient();
        tcpup.Connect(host, port2);
        var req = tcpup.GetStream();
        res = await cmd(stream, "STOR " + filename);
        if (!res.StartsWith("150 "))
        {
            throw new Exception("Upload PASV port Error!");
        }
        FileStream fs = new FileStream(fp, FileMode.Open, FileAccess.Read);
        fs.CopyTo(req);
        req.Flush();
        fs.Close();
        tcpup.Dispose();
    }

    await ReadTcp(stream);
    stream.Close();
    tcp.Close();
}

async Task<string> cmd(NetworkStream stream, string text)
{
    WriteTcp(stream,text);
    return await ReadTcp(stream);
}

void WriteTcp(NetworkStream stream, string text)
{
    if (!text.EndsWith("\r\n")) text += "\r\n";
    stream.Write(Encoding.UTF8.GetBytes(text));
}

async Task<string> ReadTcp(NetworkStream stream, bool print=true)
{
    MemoryStream ms = new MemoryStream();
    do
    {
        await Task.Delay(100);
        var bytes=new byte[4096];
        var len= stream.Read(bytes, 0, bytes.Length);
        ms.Write(bytes, 0, len);
    } while (stream.DataAvailable);
    var text= Encoding.UTF8.GetString(ms.ToArray());
    if(print) Console.WriteLine(text);
    return text;
}

标签:FTP,cmd,stream,tcpclient,text,await,res,var,上传
来源: https://www.cnblogs.com/yzpopulation/p/16382987.html