1

I want to send a text file in telegram bot for c# version 15.7.1 with the following code :

            var csvFile = new StringBuilder();
            foreach ( var person in persons)
            {
                var output = new List<string>
                {
                    person.Fardi.Name,
                    person.Fardi.LastName,
                    person.Fardi.PhoneNumber,
                    person.Fardi.BrithYear.ToString(),
                    person.Fardi.Father
                };
                csvFile.AppendLine(string.Join(_delimiter, output));
            }
            using var stream = new MemoryStream();
            using var streamWriter = new StreamWriter(stream, Encoding.UTF8);
            await streamWriter.WriteAsync(csvFile.ToString());
            await streamWriter.FlushAsync();
            await _botClient.SendDocumentAsync(new ChatId(chatId), new InputOnlineFile(stream, "test.txt"), replyMarkup: GetInlineKeyboard(buttons));

But when I send request, this error occurs :

Error while sending message
      Telegram.Bot.Exceptions.ApiRequestException: Bad Request: file must be non-empty
        at Telegram.Bot.TelegramBotClient.MakeRequestAsync[TResponse](IRequest`1 request, CancellationToken cancellationToken)

But my stream isn't empty its length is 200.

Pierre Said
  • 3,660
  • 1
  • 16
  • 28
behroozbc
  • 1,992
  • 2
  • 12
  • 25

1 Answers1

2

I have no idea what a telegram bot is, however the fix is likely as simple as rewinding the stream with MemoryStream.Position

Gets or sets the current position within the stream.

using var stream = new MemoryStream();
...
stream.Position = 0;
await _botClient.SendDocumentAsync(
    new ChatId(chatId), 
    new InputOnlineFile(stream, "test.txt"), 
    replyMarkup: GetInlineKeyboard(buttons));
TheGeneral
  • 79,002
  • 9
  • 103
  • 141