首页 > 解决方案 > 如何在字符串生成器中转换流

问题描述

我有一个 Blob 触发器,其中有一个流对象。我想将内容/文本传递给 httpclinet post call。我怎样才能做到这一点?

我有一个包含 3 行数据的 csv 文件,每列用逗号分隔

我的 CSV 中的内容:

File1,121,12123,5676,fgfg,gfg,fg,
File2,ertet,etert,ert,
File3,354345,345345
[FunctionName("Function1")]
public static void Run([BlobTrigger("expenses/{name}.csv", Connection = "AzureWebJobsStorage")]Stream inputBlob, string name,
    [Table("Expenses", Connection = "AzureWebJobsStorage")] IAsyncCollector<Expense> expenseTable,
    ILogger log)
{

这里想要将流转换inputBlob为字符串/字符串生成器,并希望获得与文件中​​的数据相同的结果。

之后,我想使用 content-type 调用(PostAsync 调用)API:text/csv 和上面提到的数据。我读到了httpclient。如果我正在使用HttpClient如何传递内容类型和请求正文

标签: c#asp.netazure-functions

解决方案


对于您的第一个问题,您可以使用StreamReader如下代码片段:

    [FunctionName("Function1")]
    public static void Run([BlobTrigger("expenses/{name}.csv", Connection = "AzureWebJobsStorage")]Stream inputBlob, string name,
    [Table("Expenses", Connection = "AzureWebJobsStorage")] IAsyncCollector<Expense> expenseTable,
    ILogger log)
    {

        //your other code

        using (StreamReader reader = new StreamReader(myBlob))
        {
            string my_content = reader.ReadToEnd();

        }
    }

对于您的第二个问题,当您使用 HttpClient 时,请将以下代码添加到您的函数中:

  [FunctionName("Function1")]
    public static void Run([BlobTrigger("expenses/{name}.csv", Connection = "AzureWebJobsStorage")]Stream inputBlob, string name,
    [Table("Expenses", Connection = "AzureWebJobsStorage")] IAsyncCollector<Expense> expenseTable,
    ILogger log)
    {

     //your other code.

     //here, use the HttpClient

     //define the http verb
     var method = new HttpMethod("POST"); 

     //add the content to body
     var request = new HttpRequestMessage(method, requestUri)
      {
            Content = new StringContent("your string to post")
      };

      //add content type
      request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/csv"));

      //send
      var httpClient = new HttpClient();
      var result = httpClient.SendAsync(request).Result;

    }

推荐阅读