Search code examples
c#sql-serverclientconnection-stringsqldatasource

C# Login Failed for User using Connection String localhost\SQLEXPRESS


I got error message when connecting my apps on client PC to the Database stored on Server PC(DESKTOP-F419755). I've tried using "localhost\SQLEXPRESS" and ".\SQLEXPRESS" but i got the same "Login Failed for user admin ..." message when trying to open connection. BUT, when i use "DESKTOP-F419755\SQLEXPRESS" for the Connection String it's works well on Client PC..

So how Client PC can connect to Server PC's Database without telling the Server PC Name.

My full Connection String was "Data Source=localhost\SQLEXPRESS;Initial Catalog=data;User ID=admin;Password=adminPass"

note: I can use either "localhost\SQLEXPRESS", ".\SQLEXPRESS", and "DESKTOP-F419755\SQLEXPRESS" on PC Server(Ofcourse).


Solution

  • So how Client PC can connect to Server PC's Database without telling the Server PC Name

    I am assuming you want to somehow mask the identity of the host in the configuration file for whatever reason. You can use the IP address directly in the connection string or add a host entry in the file: C:\Windows\System32\Drivers\etc\hosts

    DESKTOP-F419755 serverhost

    And use:

    Data Source=serverhost\SQLEXPRESS;Initial Catalog=data;User ID=admin;Password=adminPass

    Is the configuration file exposed to users? What are you trying to accomplish exactly?

    If your goal is to simply hide the machine name, this will accomplish albeit relatively half heatedly. If your primary concern is security you can pull the host name from somewhere inside the code and in the code generate the connection object therefore not needing the connection string stored in the config file.

    This all depends on what you're trying to accomplish here, you could encrypt the information in the configuration file as well or store the host name somewhere else completely (registry, etc).