[c#] Format of the initialization string does not conform to specification starting at index 0

I have an ASP.NET application which runs fine on my local development machine.

When I run this application online, it shows the following error:

Format of the initialization string does not conform to specification starting at index 0

Why is this appearing, and how can I fix it?

This question is related to c# asp.net sql-server-2008

The answer is


In my case the problem was that on the server, a different appsettings.json file was used by the application.


For the one other unfortunate soul that is managing a legacy webforms application that uses an inline sqldatasource, along with connection strings stored in web.config, then you may get this error if you access your connection string like <%APSDataConnectionString%> instead of <%$ ConnectionStrings:MyConnectionString %>. This happened to us when upgrading .NET from 3.5 to 4.x.

<asp:DropDownList ID="ddl" runat="server" DataSourceID="SqlDataSource1"
  DataTextField="value" DataValueField="id"></asp:DropDownList>                
<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
  ConnectionString="<%$ ConnectionStrings:MyConnectionString %>"
  SelectCommand="select id, value from a_table">
</asp:SqlDataSource>

I had this error too and was able to solve it as follows: I previously wrote the connectionstring to the appsettings.json into a section that I created (ConnectionsStrings (notice the extra "s") and tried to connect to my database which caused the error. It was an ASP.NET CORE application and so I wanted to connect to it with the .GetConnectionString Method (details on that here). It seems that this method implicitly searches for a connectionstring in the "ConnectionStrings"-section, which didn't exist. When I changed/corrected it to "ConnectionStrings" it worked as expected.


Set the project containing your DbContext class as the startup project.

I was getting this error while calling enable-migrations. Even if in the Package Manager Console I selected the right Default project, it was still looking at the web.config file of that startup project, where the connection string wasn't present.


Sometimes the Sql Server service has not been started. This may generate the error. Go to Services and start Sql Server. This should make it work. enter image description here


Referencing the full sp path resolved this issue for me:

var command = new SqlCommand("DatabaseName.dbo.StoredProcedureName", conn)

Make sure that your connection string is in this format:

server=FOOSERVER;database=BLAH_DB;pooling=false;Connect Timeout=60;Integrated Security=SSPI;

If your string is missing the server tag then the method would return back with this error.


I had the same problem spent an entire day. The error indicates Connection string issue for sure as index 0 is connection string. My issue was in the Startup class. I used:

var connection = Configuration["ConnectionStrings:DefaultConnection"];
services.AddControllersWithViews();
services.AddApplicationInsightsTelemetry();
services.AddDbContextPool<Models.PicTickContext>(options => options.UseSqlServer("connection"));`

which is wrong instead use this:

services.AddControllersWithViews();
services.AddApplicationInsightsTelemetry();
services.AddDbContextPool<Models.PicTickContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

and my problem was solved.


I had this error and it turned out that the cause was that I had surrounded a (new) tableadapter with a Using/End Using. Just changing the tableadapter to stay live for longer (duration of class in my instance) fixed this for me. Maybe this will help someone.


I had the same issue, came to find out that the deployment to IIS did not set the connection strings correctly. they were '$(ReplacableToken_devConnection-Web.config Connection String_0)' when viewing the connection strings of the site in IIS, instead of the actual connection string. I updated them there, and all worked as expected


As I Know, whenever you have more than 1 connection string in your solution(your current project, startup project,...), you may confront with this error

this link may help you click


Check your connection string like I forget to add services.AddDbContext<dbsContext>(options => options.UseSqlServer("Default"));

It causes the error and here when I add Configuration.GetConnectionString, then it solves the issue

like now the connection is:

services.AddDbContext<dbsContext>(options => options.UseSqlServer(Configuration.GetConnectionString("Default")));

works fine (This problem is solved for .net core)


I had typo in my connection strings "Database==PESitecore1_master"

<add name="master" connectionString="user id=sa;password=xxxxx;Data Source=APR9038KBD\SQL2014;Database==PESitecore1_master"/>

This might help someone.. My password contained a semicolon so was facing this issue.So added the password in quotes. It was really a silly mistake.

I changed the following :

<add name="db" connectionString="server=local;database=dbanme;user id=dbuser;password=pass;word" providerName="System.Data.SqlClient" />

to

<add name="db" connectionString="server=local;database=dbanme;user id=dbuser;password='pass;word'" providerName="System.Data.SqlClient" />

In my case, I got a similar error:

An unhandled exception was thrown by the application. System.ArgumentException: Format of the initialization string does not conform to specification starting at index 91.

I change my connection string from:

Server=.;Database=dbname;User Id=myuserid;Password=mypassword"

to:

Server=.;Database=dbname;User Id=myuserid;Password='mypassword'"

and it works, I added single quotes to the password.


I had the same problem. Locally the site ran fine, but on azure it would fail with the message above.

turns out the problem was setting the connectionstring in the ctor, like this:

    public DatabaseContext() 
    {
        Database.Connection.ConnectionString = ConfigurationManager.ConnectionStrings["db"].ConnectionString;
    }

Does NOT work, this will:

    public DatabaseContext() : base("db")
    {
    }

Beats me..


My problem wasn't that the connection string I was providing was wrong, or that the connection string in the app.config I thought I was using was wrong, but that I was using the wrong app.config.


I copied and pasted my connection string configuration into my test project and started running into this error. The connection string worked fine in my WebAPI project. Here is my fix.

var connection = ConfigurationManager.ConnectionStrings["MyConnectionString"];
var unitOfWork = new UnitOfWork(new SqlConnection(connection.ConnectionString));

I solved this by changing the connection string on the publish settings of my ASP.NET Web Api.

Check my answer on this post: How to fix error ::Format of the initialization string does not conform to specification starting at index 0::


My problem was I added database logging code to my constructor for a DB object, and this seemed to cause havoc on my azure deployment profile.

FYI - I simplified this example, in the real code this was turned off in production (but still in the code)

public class MyDB : DbContext
{
    public MyDB()
    {
         this.Database.Log = x => { Debug.WriteLine(x); };
    }
}

I had the same error. In my case, this was because I was missing an closing quote for the password in the connection string.

Changed from this

<add name="db" connectionString="server=local;database=dbanme;user id=dbuser;password='password" providerName="System.Data.SqlClient" />

To

<add name="db" connectionString="server=local;database=dbanme;user id=dbuser;password='password'" providerName="System.Data.SqlClient" />

I removed &quot at the end of the connection string and it worked

Instead of

App=EntityFramework&quot;

Used

App=EntityFramework;

Set DefaultConnection as below

<add name="DefaultConnection" connectionString="data source=(local);initial catalog=NamSdb;persist security info=True;user id=sa;password=sa;MultipleActiveResultSets=True;App=EntityFramework;" providerName="System.Data.SqlClient" />

Note : In connectionString Do not include :
|x| Metadata info : "metadata=res://*/"
|x| Encoded Quotes : """


I had the same problem and finally I managed to resolve it in the following way:

The problem was in the connection string definition in my web.config.

<add name="DefaultConnection" connectionString="DefaultConnection_ConnectionString" providerName="System.Data.SqlClient"/>

The above worked perfect locally because I used a local Database when I managed users and roles. When I transfered my application to IIS the local DB was not longer accessible, in addition I would like to use my DB in SQL Server. So I change the above connection string the following SQL Server DB equivalent:

<add name="DefaultConnection" connectionString="data source=MY_SQL_SERVER; Initial Catalog=MY_DATABASE_NAME; Persist Security Info=true; User Id=sa;Password=Mybl00dyPa$$" providerName="System.Data.SqlClient"/>

NOTE: The above, also, suppose that you are going to use the same SQL Server from your local box (in case that you incorporate it into your local web.config - that is what exactly I did in my case).


This also happens when you copy a web page from one solution to another, then you run your solution and find out that it has a different connection string name in the webconfig. Then you carelessly change the name of the connection string in the properties panel in the design view of the page.

Better to just change it in the code portion instead of the design.


In my case the problem was in the encoding of the connection string.

In local it worked without problems, but when installing it in a production environment it showed this error.

My application allows to set the connection string using a form and when the connection string was copied from local to production, invisible characters were introduced and although the connection string was visually identical at the byte level it was not.

You can check if this is your problem by following these steps:

  1. Copy your connection string to Notepad++.
  2. Change the codification to ANSI. In Menu Encoding>Encode to ANSI.
  3. Check if additional characters are included.

If these characters have been included, delete them and paste the connection string again.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to sql-server-2008

Violation of PRIMARY KEY constraint. Cannot insert duplicate key in object How to Use Multiple Columns in Partition By And Ensure No Duplicate Row is Returned SQL Server : How to test if a string has only digit characters Conversion of a varchar data type to a datetime data type resulted in an out-of-range value in SQL query Get last 30 day records from today date in SQL Server How to subtract 30 days from the current date using SQL Server Calculate time difference in minutes in SQL Server SQL Connection Error: System.Data.SqlClient.SqlException (0x80131904) SQL Server Service not available in service list after installation of SQL Server Management Studio How to delete large data of table in SQL without log?