Creating a Simple Console Application in SharePoint 2010

This is my first article on SharePoint 2010. In this article we will see how to create a simple Console Application in SharePoint 2010 and determine the various site users in your SharePoint site.

Creating a Console Application

Use the following procedure to create a a Console Application.

Execute Visual Studio 2010  then click "File" -> "New" -> "Project..." -> "Console Application" then give a name to the Console Application and save it.

Adding Microsoft.SharePoint.dll file to your application

Use the following procedure to add the "Microsoft.sharepoint.dll" file to your Console Application.

In Solution Explorer, right-click on the project and click "Add" -> "Reference..." then a window will open; click on ".Net" and select the "Microsoft.sharepoint.dll" and click "Ok".

Write the following code in you Console Application to determine the site users in your SharePoint site.

class Program

{

      static void Main(string[] args)

      {

            //make changes based on your site url

            string siteurl = "http://sps2010:9999/sites/kiransite/";

            using (SPSite site = new SPSite(siteurl))

            {

               //all site users in your sharepoint site

               foreach(var users in site.RootWeb.SiteUsers )

                {

                    Console.WriteLine(users);

                }

            }

            Console.ReadKey();

        }

    }

When you execute your code the first time you will get an exception called ‘File Not Found Exception’ as shown below.

File Not Found Exception

Let’s see how to handle this exception, by default in a Visual Studio 2010 Console Application, a Windows Forms application runs in 32 bit mode. But SharePoint 2010 purely built on 64 bit mode so we need to change this Console Application to 64-bit mode.

In Solution Explorer, right-click on the project and click "Properties" then a window will open; click on "Build" and change the platform target to 64-bit as shown in the following snapshot.

solution explorer

After making those changes, run your application once again, the application will run without an exception and you will see the various site users in your SharePoint site as shown below.

run your application

Summary

In this article we learned how to create a Console Application in SharePoint 2010 using Visual Studio 2010 to determine the various site users in your SharePoint site.