简体   繁体   English

C#:如何仅为文件的第一行生成 StreamContent

[英]C#: How to generate StreamContent only for first line of file

I have files with the first line as a header,我有第一行作为标题的文件,

在此处输入图片说明

Now, I have a Web API Controller code which accepts only StreamContent ,现在,我有一个只接受StreamContent的 Web API 控制器代码,

using (FileStream fs = new FileStream(@"C:\Files\test_Copy.txt", FileMode.CreateNew, FileAccess.Write))
            {
                await result.Content.CopyToAsync(fs);
            }

From client application, I am converting fileStream to StreamContent and post to Web API call.从客户端应用程序,我将fileStream转换为StreamContent并发布到 Web API 调用。

Content = new StreamContent(fileStream),

I am able to send entire file content using the below code.我可以使用以下代码发送整个文件内容。 Question: Can I send only the first line of the file as StreamContent ?问题:我可以只发送文件的第一行作为StreamContent吗?

Here I am using both client and server code in a console application,在这里,我在控制台应用程序中同时使用客户端和服务器代码,

class Program
{
    static void Main(string[] args)
    {
        Get().Wait();
    }


    public static async Task<HttpResponseMessage> Get()
    {
        using (var fileStream = new FileStream(@"C:\Files\test.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
        {
            var result = new HttpResponseMessage(HttpStatusCode.OK)
            {
                //how to send only first line of file as a "Content"
                Content = new StreamContent(fileStream),
            };

            using (FileStream fs = new FileStream(@"C:\Files\test_Copy.txt", FileMode.CreateNew, FileAccess.Write))
            {
                await result.Content.CopyToAsync(fs);
            }

            return result;
        }

    }
}

How about reading the first line into a MemoryStream and then passing that into StreamContent :如何将第一行读入MemoryStream然后将其传递给StreamContent

var memStr = new MemoryStream();
var writer = new StreamWriter(memStr);
var reader = new StreamReader(fileStream);

// Write first line to memStr
writer.Write(reader.ReadLine()); 

var result = new HttpResponseMessage(HttpStatusCode.OK)
{
    //how to send only first line of file as a "Content"
    Content = new StreamContent(memStr),
};

Note: Please ensure you dispose of the objects .注意:请确保您处理这些物品

You can use this code:您可以使用此代码:

string line1 = File.ReadLines("MyFile.txt").First(); 
byte[] byteArray = Encoding.UTF8.GetBytes( line1 );
using (var stream = new MemoryStream( byteArray ))
{
  ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM