Connection to sharepoint online using csom throws error "the underlying connection was closed an unexpected error occurred on a send"

Blaze 5 Reputation points
2023-06-09T06:04:02.5166667+00:00

CSOM code to add an user as site collection admin for all the site collections in a Online sharepoint tenant.

For the first few minutes the connection works properly. But after that the below error occurs on executing the client context

Please give your inputs on this, Thank you in advance.

System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a send. ---> System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
Microsoft 365 and Office | SharePoint | Development
Microsoft 365 and Office | SharePoint | For business | Windows
0 comments No comments
{count} vote

1 answer

Sort by: Most helpful
  1. RaytheonXie_MSFT 40,486 Reputation points Microsoft External Staff
    2023-06-09T08:46:15.79+00:00

    Hi @Blaze

    This error usually caused by TLS. You can add following code to solve the issue

    ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12;
    

    Or you can upgrate .Net Framework version after 4.6 in properties

    User's image


    If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.