nClam.ClamClient.ExecuteClamCommandAsync C# (CSharp) Method

ExecuteClamCommandAsync() private method

Helper method which connects to the ClamAV Server, performs the command and returns the result.
private ExecuteClamCommandAsync ( string command, CancellationToken cancellationToken, Func additionalCommand = null ) : Task
command string The command to execute on the ClamAV Server
cancellationToken CancellationToken cancellation token used in requests
additionalCommand Func Action to define additional server communications. Executed after the command is sent and before the response is read.
return Task
        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;
        }