C
C#7mo ago
engineertdog

✅ Content would exceed Content-Length

I have this code to add files to an HttpClient to send API requests to an external API.
c#
public void AddFile(string filePath, string fileName) {
// Open the file stream
FileStream fileStream = new(filePath, FileMode.Open, FileAccess.Read);
_fileStreams.Add(fileStream);

// Create stream content and add it to the form data.
StreamContent streamContent = new(fileStream);
streamContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
_formData.Add(streamContent, "file", fileName);
}
c#
public void AddFile(string filePath, string fileName) {
// Open the file stream
FileStream fileStream = new(filePath, FileMode.Open, FileAccess.Read);
_fileStreams.Add(fileStream);

// Create stream content and add it to the form data.
StreamContent streamContent = new(fileStream);
streamContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
_formData.Add(streamContent, "file", fileName);
}
The problem I have, is that I am getting the error Unable to write content to request stream; content would exceed Content-Length. Now, in some cases, the automated Content-Length value being set was incorrect. I have tried manually setting the content length with streamContent.Headers.ContentLength = fileStream.Length and while this does correctly set the size, I still get the same error that it would exceed the length. I'm not sure why that's occurring.
2 Replies
engineertdog
engineertdogOP7mo ago
Figured out my problem. I was clearing my _fileStreams, but I needed to also _formData.Dispose() and then create a new object.
MODiX
MODiX7mo ago
If you have no further questions, please use /close to mark the forum thread as answered
Want results from more Discord servers?
Add your server