Click here to Skip to main content
15,886,689 members
Articles / Productivity Apps and Services / Sharepoint / SharePoint 2010

Comprehensive C# watch-folder for SharePoint

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
27 Mar 2016CPOL3 min read 17.9K   1
This is a comprehensive windows C# application which watches specific folders and upload their entry to a SharePoint lists or document library

Introduction

This is a complete windows application that works with Microsoft SharePoint. F2S is a watch-folder, watching specific folders. It adds their names into SharePoint lists or uploads them into SharePoint Document Library.

F2S works based on “Watchers”. In the application, you can create many Watchers, each watcher gets the following properties and saves them into a MS-SQL Server database: SharePoint site URL, SharePoint application, List name and path which must be watched.

This application works with multi-threading design, therefore the routine is not interrupted when a new file is found in a specific folder. Also, F2S connects to SharePoint with a custom DLL file (SPWebServiceLink), this is a very professional class library that connect to the SharePoint via SharePoint’s web services and simulates a Dataset to be used in the guest application. I will share with you the source code of “SPWebServiceLink” in my next articles.

Background

I am working with SharePoint since 2005. I created this application for a Media Company who has a Fileservers to save its entry clips (It was more than 1000 clips/hour). The company had switched its data server to a SharePoint and one of their important requirements was to enter name of clips into SharePoint lists.

I developed this application for them. This application handles their problem and it’s good to hear that the application is working from 2008 up to now without any debugging.

Using the Code

This is a complete application and I can’t describe all of its details, but I try to share some of most important issues with you. I can also help you if you decide to use the application as a solution in your company.

  1. mainForm is the core of this application. This is the main form of this application and all other user-controls are opening in the main panel “pnlMain” of the mainForm. There is a custom control in the left bar of the main form called “OpenFormTree”. You can see its code on this application too. This control, saves the information of open forms and gives the application the abilities for forms surfing.
  2. Main form has a Watchers’ property which is an ArrayList and saves all the information of Watcher controls. As I described above, in this application, you can have one or many watchers. Each watcher watches a specified folder and uploads its file names into a Sharepoint list or uploads files into a SharePoint Document Library.
  3. When the application runs, main form’s Load handler is called. This method also calls another method “RestartWatching()” this method reads all watchers info from the database and loads them into Watchers property.
C#
private void RestartWatching()
{
    foreach (TreeNode t in this.openFormTree1.Nodes)
    {
        if (t.Text=="Watching Status...")
        {
            MessageBox.Show("You have to close SSP Watching now & Run again.", 
                 "Restart Watching", MessageBoxButtons.OK, MessageBoxIcon.Error);
            Application.Exit();

            return;
        }
    }

    _Watchers = new System.Collections.ArrayList();
    SSPWatchFolderDatatsetTableAdapters.SSPWatchFolder_FoldersTableAdapter adp = 
      new F2S_WS.SSPWatchFolderDatatsetTableAdapters.SSPWatchFolder_FoldersTableAdapter();
    SSPWatchFolderDatatset dst = new SSPWatchFolderDatatset();
    adp.Fill(dst.SSPWatchFolder_Folders);

    foreach (SSPWatchFolderDatatset.SSPWatchFolder_FoldersRow r in dst.SSPWatchFolder_Folders.Rows)
    {
        try
        {
            SPWebServiceLink.WS_SPList li = new SPWebServiceLink.WS_SPList(r.Folder_SiteURL, _NC);

            string rootFolder = li.GetRootFolder(r.Folder_ListID);

            Uri u = new Uri(r.Folder_SiteURL);
            string rootUrl = u.Scheme + "//" + u.Host + ":" + u.Port.ToString();

            F2S_WS.Controls.WatcherController _watcher = new F2S_WS.Controls.WatcherController();
            _watcher.WatcherLastCheck = r.Folder_LastCheck;
            _watcher.WatcherListID = r.Folder_ListID;
            _watcher.WatcherName = rootFolder;
            _watcher.rootURL = rootUrl;
            _watcher.WatcherPath = r.Folder_Path;
            _watcher.WatcherSiteTimeDif = r.Folder_TimeDif;
            _watcher.WatcherSiteURL = r.Folder_SiteURL;
            _watcher.WatcherMode = r.Folder_Mode;
            _watcher._NC = _NC;

            _watcher.FSWStart();

            _Watchers.Add(_watcher);
        }
        catch
        {

        }
    }
...

The watcher control has the following properties that include all the needed data:

C#
public string WatcherPath = "-";
public DateTime WatcherLastCheck = new DateTime();
public string WatcherName = "-";
public string WatcherListID = "-";
public string WatcherListName = "-";
public string WatcherWebID = "-";
public string WatcherWebName = "-";
public string WatcherSiteURL = "-";
public long WatcherSiteTimeDif = 0;
public string WatcherMode = "List";
public bool Started = false;
public string rootURL;
public FileSystemWatcher fsw;
public System.Net.NetworkCredential _NC;
private SPWebServiceLink.WS_SPList _SPList;
private SPWebServiceLink.WS_DocumentWorkSpace _DocumentWorkSpace;
private SPWebServiceLink.WS_Copy _Copy;
private  DataSet listDataset;

The Watcher control works based on “FileSystemWathcer”, which is configured in the FSWStart() method. As you can see in the following code in the FSWStart() method, all configurations and settings are done and it starts watching.

C#
public void FSWStart()
{
    fsw = new FileSystemWatcher();
    try
    {
        fsw.Path = this.WatcherPath;

        fsw.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
        | NotifyFilters.FileName | NotifyFilters.DirectoryName;

        fsw.Filter = "*.*";

        fsw.Created += new FileSystemEventHandler(OnChanged);

        fsw.IncludeSubdirectories = true;

        fsw.EnableRaisingEvents = true;
        fsw.SynchronizingObject = txtStatus;
        WriteNewLineLog("Watcher Started ...");

        _SPList = new SPWebServiceLink.WS_SPList(WatcherSiteURL, _NC);
        _DocumentWorkSpace = new SPWebServiceLink.WS_DocumentWorkSpace(WatcherSiteURL, _NC);
        _Copy = new SPWebServiceLink.WS_Copy(WatcherSiteURL, _NC);

        listDataset = _SPList.GetListSchema(WatcherListID);

        this.Started = true;
        timer1.Enabled = true;
    }
    catch (System.Exception ex)
    {
        this.Started = false;
        fsw.EnableRaisingEvents = false;
        WriteNewLineLog("Watcher can not be started ...");
        WriteNewLineLog("F2S ERRROR - er453#e - " + ex.Message);                
    }    
}

Each Watcher works with its own FileSystemWatcher, therefore each Watcher has two handlers for handling FileSystemWatcher events.

C#
public void OnChanged(object source, FileSystemEventArgs e)
{
    try
    {
        WriteNewLineLog("Watcher found new file, Named: " + e.FullPath);        

        if (WatcherMode == "List")
        {
            string[] sp1 = { "\\" };
            string[] folders = e.Name.Split(sp1, StringSplitOptions.RemoveEmptyEntries);

            CreateListTodayFolder();

            if (System.IO.File.Exists(e.FullPath))
            {
                UploadListItem(e.FullPath,"");
            }
            else
            {
                UpLoadDirectoryContentsToList(e.FullPath, 1);
            }

            //string colName = "";
            //for (int i = 0; i < dd.Tables[0].Columns.Count; i++)
            //{
            //    colName += dd.Tables[0].Columns[i].ColumnName + "-->" + 
            //    dd.Tables[0].Rows[1][dd.Tables[0].Columns[i].ColumnName].ToString() + "\r\n";
            //}
            //System.IO.File.WriteAllText("c:\\t.txt", colName, System.Text.Encoding.UTF8);

            WriteNewLineLog("Watcher create new item in Link List");
        }
        else
        {
            string[] sp1 = { "\\" };
            string[] folders = e.Name.Split(sp1, StringSplitOptions.RemoveEmptyEntries);

            CreateTodayFolder();
            if (System.IO.File.Exists(e.FullPath))
            {
                UpLoadFile(e.FullPath,"");
            }
            else
            {
                UpLoadDirectoryContents(e.FullPath, 1);
            }
        }
    }
    catch (Exception ex)
    {
        string ss = ex.Message;
        WriteNewLineLog("F2S ERROR - 1f56");
    }

Also, there are 2 User-Controls and a base class on the UC folder:

  1. SSPW_FoldersList

    This user-control gives users abilities to manage the folder which must be watched and controlled:

  2. SSP_WatcherControllerList

    This user-control contains all active Watching controls in Watcher array-list.

If you have any questions or suggestions to make this article more useful, please do not hesitate to contact me via the comments section below.

Any commercial use of this application is only allowed in coordination with the writer.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Sweden Sweden
Mehdi Mohseni is a Software senior developer (Consultant) in Sigma ITC (www.sigmait.se), Mehdi has a deep experience in N-Tier software applications as well as MVC design pattern. Mehdi has led more than 100 Asp.Net C# or VB.Net Automation applications. Mehdi is working in Toyota Material Handling Logistic Solution as Senior .Net Developer now.

Comments and Discussions

 
QuestionFormat problem Pin
Nelek27-Mar-16 6:07
protectorNelek27-Mar-16 6:07 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.