FTP tcpclient 上传文件

2022/6/16 23:20:15

本文主要是介绍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 tcpclient 上传文件的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程