1

I want to add multiple streams into my MultiformDataContent and I'm doing it like this:

 MultipartFormDataContent formdata = new MultipartFormDataContent();
 foreach (var item in files)
 {
     using (FileStream fs = File.Open(item, FileMode.Open, FileAccess.Read))
     {
         HttpContent content = new StreamContent(fs);
         formdata.Add(content, "files", item.Split(charSeparators)[2]);
     }
}
// send the content to the backend, parse results
var result = client.PostAsync(url, formdata).Result; // ObjectDisposedException

but when I check my content length, it's null and the ObjectDisposedException is thrown.

0

1 Answer 1

4

This line simply wraps fs in a StreamContent object.

HttpContent content = new StreamContent(fs);

The stream isn't read until you call PostAsync:

client.PostAsync(url, formdata)

At which point you have already closed the stream. You should dispose of the stream after you have posted it. MultipartFormDataContent will dispose of any content objects it contains, and that will in term dispose of the stream, so you can rewrite your code as follows:

using(MultipartFormDataContent formdata = new MultipartFormDataContent())
{
    foreach (var item in files)
    {
        FileStream fs = File.Open(item, FileMode.Open, FileAccess.Read);
        HttpContent content = new StreamContent(fs);
        formdata.Add(content, "files", item.Split(charSeparators)[2]);
    }
    // send the content to the backend, parse results
    var result = client.PostAsync(url, formdata).Result;
}

Proof that it disposes correctly.

Sign up to request clarification or add additional context in comments.

2 Comments

I've done that but now it throws an exception on the fact that I'm trying to use the same file for multiple processes (I'm using mock files)
@Mout I suspect you'll need to pass a 4th parameter to File.Open: FileShare.Read to allow you to open multiple read streams to the same file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.