npgsql trouble in c# app - An existing connection was forcibly closed by the remote host

10,707

I had spent 1 hour searching same and found no issues. But then realized that PG puts its logs in pg_log folder. I looked in it to see possible issue.

It turn out you just need to have correct "host" entry in "pg_hba.conf" file. For me this file is in C:\Program Files\PostgreSQL\9.1\data directory. For example

host all all 192.168.1.2/32 md5

Where 192.168.1.2 - is your client's ip address.

BTW, you still need to have 5432 port open as Inboud rule (windows Vista, Windows 7, Windows 2008+).

Share:
10,707
Omniabsence
Author by

Omniabsence

Updated on June 16, 2022

Comments

  • Omniabsence
    Omniabsence almost 2 years

    I am getting the following error when trying to open my Postgresql database from a C# utility:

    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

    I have tried running this program from a remote computer and from the computer on which the Postgresql server is running.

    There are no firewalls on either computer at this moment and I am able to connect to the database and server just fine through the postgres admin utility using the same password. I have checked that the username has permissions to the database.

    Here is my code for the connection:

    public bool updateFromServer()
    {
        try
        {
            NpgsqlConnection conn = new NpgsqlConnection(connString);
            conn.Open();
            conn.Close();
            return true;
        }
        catch (Exception e)
        {
            conn.close()
            return false;
        }
    }
    

    Any help with this would be appreciated.

  • coffekid
    coffekid over 11 years
    Thanks a lot, this was a life-saver really.