Search code examples
c#npgsql

Npgsql Connection Forcibly Closed C#


I don't know why but whenever I try to connect to my database this happens

SocketException: An existing connection was forcibly closed by the remote host.

I'm using C# and Npgsql with my connection.json is like this

{
  "server": "localhost",
  "port": "5432",
  "database": "Postgres2",
  "userID": "postgres",
  "password": "admin"
}

and my code looks like this

string serverConfigLocation = "Data/conn.json";
async void Start()
{
    var cS = new ConnectionString();
    if(File.Exists(serverConfigLocation))
    {
        using (StreamReader r = new StreamReader(serverConfigLocation))
        {
            var json = r.ReadToEnd();
            cS = ConnectionString.FromJson(json);
        }
    }
    
    System.Net.ServicePointManager.SecurityProtocol = 
    System.Net.SecurityProtocolType.Tls | 
    System.Net.SecurityProtocolType.Tls11 | System.Net.SecurityProtocolType.Tls12;
    var connectionString = "Host=" + cS.server + ";Username=" + cS.userID + ";Password=" 
    + cS.password + ";Database=" + cS.database;

    await using var conn = new NpgsqlConnection(connectionString);
    await conn.OpenAsync();
}

Solution

  • Done, I reinstalled my PgAdmin and PostgreSql and it worked like a charm. Don't know how that happen though.