This project is read-only.

Cannot access closed stream file upload

Topics: Web Api
Oct 12, 2011 at 12:14 PM

Hi I am trying to implement the file upload provided in the samples.   I am getting "Cannot access a closed stream" from the trygetformfieldvalue when trying to get the submitter content.  I thought it may be image size but tried with a very small file and also set MaxReceivedMessageSize in config. Can anybody give any pointers as to what I should be looking at.



Oct 12, 2011 at 3:39 PM

When the file content is written to disk we close the write stream afterwards in order not to have open write streams so that stream can’t be used anymore. This means that if you want to read the file content then you have to create a read stream and read the contents.

TryGetFormFieldValue is intended to read the text fields (the normal input fields in the HTML form), not the file content itself.

If you want the file contents just read into memory (and not to disk) then you can use the default stream provider (implicitly used if you don’t indicate any stream provider). That will read all contents into memory using MemoryStreams which can be read directly again.

An example using just the default provider looks like this:

[WebInvoke(UriTemplate = "", Method = "POST")]

public List<Contact> UploadContacts(HttpRequestMessage request)


if (!request.Content.IsMimeMultipartContent())


throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);


// Read the MIME multipart content

IEnumerable<HttpContent> bodyparts = request.Content.ReadAsMultipart();

// The actual data is the entity with a Content-Disposition header field

// with a "name" parameter with value "data"

HttpContent dataContent = bodyparts.FirstDispositionNameOrDefault("data");

if (dataContent != null)


// Read contents which deserializes the content based on the content type.

// The browser typically sets the content type if it knows about the file

// extension. However, if it doesn't set it then it is possible to set

// here.

var contacts = dataContent.ReadAs<List<Contact>>();

return contacts;


return new List<Contact>();