How to all messages on Azure Storage Queue without dequeuing in C#

201 Views Asked by At

I have an Azure Storage Queue and want to create a service to view the contents of for admin-purposes. I know I can view the queue using Storage Explorer, but I want to be able to view the messages (and their contents) in a C# application.

From what I can see, the API allows me to get the write to and pop from the head of the queue, but I need to see all messages without removing them.

2

There are 2 best solutions below

1
Kevin On BEST ANSWER

What you need to use is PeekMessagesAsync, with that you can peek the first X messages in the queue. Example:

// Create a QueueClient.
var queueClient = new QueueClient("your-storage-account", "your-queue-name");

// Peek at the first 32 messages in the queue.
var messages = await queueClient.PeekMessagesAsync(32);

Next you can do whatever you want with it.

1
Rafal Kozlowski On

try using the following code:

public static class DryRunIterator
{
    public static async IAsyncEnumerable<ServiceBusReceivedMessage> GetMessages(string connectionString, string queueName, int prefetchCount)
    {
        await using var serviceBusClient = new ServiceBusClient(connectionString);

        await using var deadLetterReceiver = serviceBusClient.CreateReceiver(queueName, new ServiceBusReceiverOptions() { PrefetchCount = prefetchCount, ReceiveMode = ServiceBusReceiveMode.PeekLock });
        long? lastReceivedSequenceNumber = null;

        while (true)
        {
            var messages = await deadLetterReceiver.PeekMessagesAsync(prefetchCount, lastReceivedSequenceNumber + 1);

            if (messages.Count == 0)
                break;

            foreach (var message in messages)
            {
                yield return message;

                lastReceivedSequenceNumber = message.SequenceNumber;
            }
        }

        await deadLetterReceiver.CloseAsync();
    }
}

it uses Azure.Messaging.ServiceBus.

Hope this helps.