Files
DearFTP/DearFTP/Connection/FtpStream.cs
2019-07-20 12:52:41 +02:00

82 lines
2.0 KiB
C#

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
namespace DearFTP.Connection
{
class FtpStream
{
public const int BUFFER_SIZE = 4096;
public Stream Stream { get; }
public FtpStream(Stream stream)
{
Stream = stream;
}
public (string command, string argument) Receive()
{
var buffer = new byte[BUFFER_SIZE];
int readBytes = Stream.Read(buffer, 0, buffer.Length);
if (readBytes == 0)
{
return ("END", "");
}
string packet = Encoding.UTF8.GetString(buffer, 0, readBytes);
if (!packet.EndsWith("\r\n"))
{
throw new Exception("Ftp packet is in wrong format");
}
packet = packet.Remove(packet.Length - 2);
string[] split = packet.Split(' ');
string command = split[0];
string argument = string.Join(' ', split.Skip(1));
return (command, argument);
}
public void Send(string message, bool end = true)
{
var bytes = Encoding.UTF8.GetBytes($"{message}{(end ? "\r\n" : "")}");
Stream.Write(bytes, 0, bytes.Length);
}
public void Send(ResponseCode code, string argument)
{
var bytes = Encoding.UTF8.GetBytes($"{(uint)code} {argument}\r\n");
Stream.Write(bytes, 0, bytes.Length);
}
public void Send(ResponseCode code, string message, params string[] arguments)
{
var builder = new StringBuilder();
builder.Append($"{(uint)code}-{message}\r\n");
foreach (string argument in arguments)
{
builder.Append($" {argument}\r\n");
}
builder.Append($"{(uint)code} End\r\n");
var bytes = Encoding.UTF8.GetBytes(builder.ToString());
Stream.Write(bytes, 0, bytes.Length);
}
}
}