Most of us might have seen this error while creating a custom application (console application, Windows application or custom web part) using Visual Studio targeting for SharePoint 2010. It’s not just this specific error but a lot of other weird error messages without any reason. The above error occurs when we create a new SPSite object using a site URL with following code.
SPSite site = New SPSite (<site URL>);
When we check the web application and site mentioned in <site URL> it exists and can be browsed in browser! Looks like there is no reason for Visual Studio to show this error. But stop yelling at Visual Studio; there is a reason. You haven’t selected the right CPU version for the target application (x64 v/s x86). The reason behind this is, SharePoint 2010 works only on a 64-bit platform but Visual Studio is a 32-bit application. When we open a project in Visual Studio, the default target platform selected is 32-bit. When you compile your custom application, it creates binaries for 32-bit platform which doesn’t work on a 64-bit platform as the way it is expected to be.
So how can we avoid this error? Just change the target platform to x64 in Project Properties > Build section. It’s also recommended to create reference to corresponding assemblies. For example,