user584018
user584018

Reputation: 11354

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

I have files with the first line as a header,

enter image description here

Now, I have a Web API Controller code which accepts only StreamContent,

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.

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?

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;
        }

    }
}

Upvotes: 1

Views: 2860

Answers (2)

Fred
Fred

Reputation: 3431

You can use this code:

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

Upvotes: 1

CodingYoshi
CodingYoshi

Reputation: 27039

How about reading the first line into a MemoryStream and then passing that into 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.

Upvotes: 1

Related Questions