private async Task<string> ExecuteClamCommandAsync(string command, CancellationToken cancellationToken, Func<NetworkStream, CancellationToken, Task> additionalCommand = null)
{
#if DEBUG
var stopWatch = System.Diagnostics.Stopwatch.StartNew();
#endif
string result;
var clam = new TcpClient();
try
{
await clam.ConnectAsync(Server, Port).ConfigureAwait(false);
using (var stream = clam.GetStream())
{
var commandText = String.Format("z{0}\0", command);
var commandBytes = Encoding.UTF8.GetBytes(commandText);
await stream.WriteAsync(commandBytes, 0, commandBytes.Length, cancellationToken).ConfigureAwait(false);
if (additionalCommand != null)
{
await additionalCommand(stream, cancellationToken).ConfigureAwait(false);
}
using (var reader = new StreamReader(stream))
{
result = await reader.ReadToEndAsync().ConfigureAwait(false);
if (!String.IsNullOrEmpty(result))
{
//if we have a result, trim off the terminating null character
result = result.TrimEnd('\0');
}
}
}
}
finally
{
if (clam.Connected)
{
clam.Close();
}
}
#if DEBUG
stopWatch.Stop();
System.Diagnostics.Debug.WriteLine("Command {0} took: {1}", command, stopWatch.Elapsed);
#endif
return result;
}