When dealing with SharePoint, the code for a WebPart or User Control is ‘within’ the scope of IIS – and thus there is an SPContext you can use.
But – if you try code from a Console App – you might get this error :
System.IO.FileNotFoundException: The Web application at <URL> could not be found
The code I’ve been developing is similar to this :
using (SPSite site = new SPSite(sourceWebUrl))
using (SPWeb web = site.OpenWeb())
And – the above error (not found) was happening on the first line. Some searching around highlighted the following tips :
When developing against the SharePoint object model in an application outside of IIS (service, console, Winforms etc..) you receive the error “FileNotFoundException” when creating an instance of the SPSite object.
The user running the application needs to have the following permissions and group membership set:
- The user is a server farm administrator.
- The user has Read and Write permissions on the content database.
- The user is a site collection administrator.
- The user has permissions to access the Windows SharePoint Services site or the SharePoint Server 2007 site through which the code iterates.
Source : MSDN (question #10)
UPDATE : Also need to ensure the user has Read and Write permissions on the config database also (not just content, config as well)
BUT – this didn’t fix the problem… WTF !?
The solution – as it turns out – when dealing with SharePoint 2010 is the “platform target”.
When you add a new solution/project in Visual Studio, the default is “x86” (32-bit) – and this needs to be changed to “x64” (64-bit) – as SharePoint 2010 is 64-bit (only).
- Right-click on the solution/project
- Click Properties
- Switch to the “Build” tab
- Make sure to change the dropdown to x64
- Re-build + run the project
- Hopefully, that fixed the problem !
- Well – it fixed it for ME anyways.
Good luck !