Hi All,
I have some large files in my environment, exceeding 1GB in size, and I'm attempting to upload them to a SharePoint online site using the C# SharePoint REST API. However, I'm encountering an error message that says, "Connection forcibly closed by host" when I try to upload these files. The code works well with files less than 150MB.
Below is the relevant code. Could someone please confirm how to achieve this successfully?
static async Task PutUploadLargeFileAsync(string accessToken, string filePath, string sharePointUrl, string libraryName)
{
using HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
client.Timeout = TimeSpan.FromMinutes(20);
var fileStream = new FileStream(filePath, FileMode.Open);
var fileName = Path.GetFileName(filePath);
var requestUri = $"{sharePointUrl}/_api/web/lists/getbytitle('{libraryName}')/RootFolder/Files/Add(url='{fileName}', overwrite=true)";
var response = await client.PutAsync(requestUri, new StreamContent(fileStream));
if (response.IsSuccessStatusCode)
{
Console.WriteLine("File uploaded successfully.");
}
else
{
Console.WriteLine($"File upload failed. Status code: {response.StatusCode}");
}
}