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;
}

原创文章,作者:745907710,如若转载,请注明出处:https://blog.ytso.com/268051.html

(0)
上一篇 2022年6月19日
下一篇 2022年6月19日

相关推荐

发表回复

登录后才能评论