Search code examples
c#sharepoint-2010powershell-2.0filenotfoundexceptionspsite

Why can I get SPSite in PowerShell but fails with FileNotFound in c#?


We have a mixed (forms and Windows)-based SharePoint 2010 site and I'm attempting to use the object model in c# (command line console app, referenced to Microsoft.SharePoint, Solution Platform target is x64 [in VS 2012 I had to create a new solution platform, settings copied from <Empty>].)

In PowerShell, I can simply do something like

$site = Get-SPSite http://www.server.com/sites/site1

It successfully retrieves the object, and I can open the contained SPWebs, etc. as I please. However, when I attempt similar logic in C# (on the same box under the same user credentials) like

using(SPSite site = new SPSite("http://www.server.com/sites/site1") { }

it fails with the FileNotFoundException. Any attempts to use the associated Guids follow the same issue. Why might this be happening?

Also, I am an administrator on the box and also explicitly have sysadmin server role on the database.


Solution

  • For anyone experiencing this as well. PowerShell 3 does not support SharePoint methods. I discovered after installing Powershell v3 that I had to enter another shell using the command powershell -version 2 first before running SharePoint commands, which led me to realize that my VS project was targeting .NET 4.5; Once I changed it to .NET 3.5, everything worked.

    I assume that despite the SharePoint libraries targeting .NET 3.5, and theoretically the .NET 4 CLR can handle .NET 2 CLR libraries, Projects with usage of SharePoint 2010 do not support targeting .NET 4/4.5 in any way.

    Happy to be proved wrong, of course ;)