Search code examples
botframework

How to send user a CSV file which is created by bot C# BotFramework SDK3


As the title, I want to send user a CSV file which is created by bot C# BotFramework SDK3.. I'm going to use webchat. Let user Download it or Copy the users Desktop. Either way is ok. Is it possble?


Solution

  • If your CSV file is stored in your project folder, to send a CSV file to the user(s), you can refer to the following sample code.

    var replymes = context.MakeMessage();
    replymes.Text = "Here is a CSV file.";
    
    replymes.Attachments.Add(await GetCSVAttachmentAsync(replymes.ServiceUrl, replymes.Conversation.Id));
    
    await context.PostAsync(replymes);
    

    The implementation of GetCSVAttachmentAsync:

    private static async Task<Attachment> GetCSVAttachmentAsync(string serviceUrl, string conversationId)
    {
        var filePath = System.Web.HttpContext.Current.Server.MapPath(@"~\csv_files\userinfo.csv");
    
        using (var connector = new ConnectorClient(new Uri(serviceUrl)))
        {
            var attachments = new Attachments(connector);
            var response = await attachments.Client.Conversations.UploadAttachmentAsync(
                conversationId,
                new AttachmentData
                {
                    Name = "userinfo.csv",
                    OriginalBase64 = System.IO.File.ReadAllBytes(filePath),
                    Type = "text/csv"
                });
    
            var attachmentUri = attachments.GetAttachmentUri(response.Id);
    
            return new Attachment
            {
                Name = "userinfo.csv",
                ContentType = "text/csv",
                ContentUrl = attachmentUri
            };
        }
    }
    

    Test result:

    enter image description here

    Update:

    Store the CSV file in Azure storage blob, and send it as attachment.

    var storageAccount = CloudStorageAccount.Parse("{storage_connection_string}");
    
    var blobClient = storageAccount.CreateCloudBlobClient();
    var cloudBlobContainer = blobClient.GetContainerReference("mycontainer");
    cloudBlobContainer.CreateIfNotExists();
    
    var cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference("userinfo.csv");
    
    cloudBlockBlob.UploadFromFile(System.Web.HttpContext.Current.Server.MapPath(@"~\csv_files\userinfo.csv"));
    
    var url = cloudBlockBlob.Uri.ToString();
    
    return new Attachment
    {
        Name = "userinfo.csv",
        ContentType = "text/csv",
        ContentUrl = url
    };