Skip to main content
Email Password   helpLost your password?

Introduction

This article describes uploading files in a sequence to a SharePoint Document Library and then using CAML, updating each file's custom meta data. This article also also describes how to use DWS web service to create folders/subfolders in a Doc Lib and how to use List web service to upload/update files inside Doc Lib.

Background

In my organization, a large number of documents are scanned each day (.pdf) and we maintain an electronic complex system of approving documents and filtering/searching based on there respective meta data. Files are named in a specific manner, I had to write a Web Service named File Shunter in Vb.Net which contains two functions, 1 function takes the input folder and upload the files to server into a specific folder (this function also creates folders/subfolders based on rules in file name using SharePoint DWS Web service), the other function, for each document being uploaded, extracts all the required meta data from the file name and once the file has been uploaded, using CAML and List Web service (http://sp portal/subsite/_vti_bin/lists.asmx) updates the required meta data columns for that file. I use Web.config to store/retreive doc library name, portal name, user authentication etc... . This code uses web services, so it is not required to run the code on the server where portal is running (in case where SharePoint Object Model is used). Another feature is we have to maintain version history of each file since a file can be uploaded multiple times so we need to keep its revisions, for this purpose, if version history is enabled in document library and if a file's meta data is changed after it has been uploaded, it will become a new version while we need to access and update the current file without making anotehr version while updating it for this purpose the function bEnableVersion(True/false) is used, which is set true when uploading teh file so that if file already exists then a version is generated inside doc lib but when updating its meta data, version history is set to false (bEnableVersion(false)). Another good feature of a document library is that it can be used as a mapped drive inside file system (since its a web folder). Our documentation dept was used to of accessing files from a shared folder before, now after files are uploaded to SharePoint, we just mapped that document library as a shared folder for each user so there is no difference for them to work/access these files, Just enable the WebClient service on user's PC and map the doc lib (http://portal/site/doclib).

Using the code

There are two main functions: UploadDocument and WSSUpdateFile. The 1st function is passed Local file name (On file system) and remote file name (to be used inside doc lib. Once the file is uploaded, the other function is passed file name, and any meta data column values to be updated, for test purpose, i created a column named "TestCol" in my test document library and passed it "Test Value", but this function can be passed as many number of meta data column values as required, just add them in the xml batch inside the function with column name and the value. To update a file properties, normally its ID is required to access it and update its properties (even inside folders). I have used CAML (Access the recent uplaoded file and get its ID) then this ID is used in List Web service UpdateListItems function to update the properties of the file. Included is function "CreateFolder" which can be used to create any number of folder/subfolders within a Doc Lib. Most of the common required values like Portal URL, Doc Lib name, user, pwd, domain, folder name (where files reside to be uploaded) are set into Web.config for easy modification. Main function access these values to determine required data and authentication. To upload teh files lets say from D:\Test folder, in web.config under globalsharedpath key "<add key="GlobalSharedPath" value="D:\"/>" Pass only "D:\" and once the program is running, pass only "Test" in the input folder name. 1 thing to remember is that some of SharePoint web services are site specific, means u need to reference the exact site/subsite to play with it, for example if i have a subsite under http://portal/sitedirectory/site then list web servic erefernce should be like http://portal/sitedirectory/site/_vti_bin/lists.asmx.

//
Web.config
<configuration>
<appSettings>

<add key="SharePointServer" value=http://SP Portal/Site/>
<add key="DocLibrary" value="Doclib"/>
<add key="User" value="User"/>
<add key="Domain" value="Domain"/>
<add key="Pwd" value="Pwd"/>
<add key="GlobalSharedPath" value="D:\"/>
</appSettings>
//
Public Function UploadDocument(ByVal localFile As String, ByVal remoteFile As String) As String
        '// Read in the local file
        On Error GoTo handler
        Dim r As Byte()
        Dim Strm As System.IO.FileStream = New System.IO.FileStream(localFile, System.IO.FileMode.Open, System.IO.FileAccess.Read)
        Dim reader As System.IO.BinaryReader = New System.IO.BinaryReader(Strm)
        Dim filecontents As Byte() = reader.ReadBytes(CInt(Strm.Length))
        reader.Close()
        Strm.Close()
        Dim sSPURL As String = ConfigurationManager.AppSettings("SharePointServer")
        Dim sDocLib As String = ConfigurationManager.AppSettings("DocLibrary")
        Dim sUser As String = ConfigurationManager.AppSettings("User")
        Dim sPwd As String = ConfigurationManager.AppSettings("Pwd")
        Dim sDomain As String = ConfigurationManager.AppSettings("Domain")
        Dim sRemoteFileURL As String
        Dim NC As System.Net.NetworkCredential = New System.Net.NetworkCredential(sUser, sPwd, sDomain)
        sRemoteFileURL = sSPURL & "/" & sDocLib & "/" & Trim(LTrim(RTrim(remoteFile)))
       
        sRemoteFileURL = Replace(sRemoteFileURL, " ", "%20")
        sRemoteFileURL = Replace(sRemoteFileURL, "\", "/")
        Dim m_WC As WebClient = New WebClient
        m_WC.Credentials = NC
        r = m_WC.UploadData(sRemoteFileURL, "PUT", filecontents)
        Return "TRUE"
        Exit Function
handler:
        Return Err.Description
    End Function



Public Function WSSUpdateFile(ByVal sFileName As String, ByVal sSiteDoc As String, ByVal sTestCol As String) As String
        Dim sUser As String = ConfigurationManager.AppSettings("User")
        Dim sPwd As String = ConfigurationManager.AppSettings("Pwd")
        Dim sDomain As String = ConfigurationManager.AppSettings("Domain")
        Dim sFileIDinList As String
        Dim strBatch As String = ""
        sSiteDoc = Replace(sSiteDoc, "%20", " ")
        sSiteDoc = Replace(sSiteDoc, "\", "/")
        Dim sFinalFilePath As String
        Dim sSPURL As String = ConfigurationManager.AppSettings("SharePointServer")
        Dim sDocLib As String = ConfigurationManager.AppSettings("DocLibrary")
        Try
            Dim netAccess As System.Net.NetworkCredential = New System.Net.NetworkCredential(sUser, sPwd, sDomain)
            Dim listService As New SPLists.Lists
            listService.Url = sSPURL & "/_vti_bin/lists.asmx"
            listService.Credentials = netAccess
            sFileIDinList = sGetID(listService.Url, sDocLib, sFileName)
            If sFileIDinList <> "" Then
                sFinalFilePath = sSPURL & "/" & sDocLib & "/" & sFileName
                'Now we have FileID so update the list
                strBatch = "<Method ID='1' Cmd='Update'>" + _
                    "<Field Name = 'ID'>" & sFileIDinList & "</Field>" + _
                    "<Field Name = 'FileRef'>" & sFinalFilePath & "</Field>" + _
                    "<Field Name = 'TestCol'>" & sTestCol & "</Field>" + _
                    "</Method>"
                Dim xmlDoc = New System.Xml.XmlDocument
                Dim elBatch As System.Xml.XmlElement = xmlDoc.createelement("Batch")
                elBatch.InnerXml = strBatch
                Dim ndreturn As System.Xml.XmlNode = listService.UpdateListItems(sDocLib, elBatch)
            End If
            Return "TRUE"
        Catch ex As Exception
            Return ex.Message
        End Try
    End Function
Private Function sGetID(ByVal sURL As String, ByVal sListGUID As String, ByVal sFileName As String) As String
        Dim sUser As String = ConfigurationManager.AppSettings("User")
        Dim sPwd As String = ConfigurationManager.AppSettings("Pwd")
        Dim sDomain As String = ConfigurationManager.AppSettings("Domain")
        Dim netAccess As System.Net.NetworkCredential = New System.Net.NetworkCredential(sUser, sPwd, sDomain)
        Dim L As New SPLists.Lists
        L.Credentials = netAccess
        L.Url = sURL
        Dim xmldoc As XmlDocument = New XmlDocument
        Dim query As XmlNode = xmldoc.CreateNode(XmlNodeType.Element, "Query", "")
        query.InnerXml = "<OrderBy><FieldRef Name='Modified'  Ascending='False'></FieldRef></OrderBy>"""
        Try
            Dim caml As XmlNode = L.GetListItems(sListGUID, Nothing, query, Nothing, "1", Nothing)
            Dim id As String = caml.ChildNodes(1).ChildNodes(1).Attributes("ows_ID").Value
            Return id
        Catch ex As Exception
            Return ex.Message
        End Try
    End Function


Points of Interest

Using Web services instead of OM Creating folders inside Doc Lib Enabling/Disabling Version History
You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
GeneralGetListItems parameters? [modified] Pin
mayshar
16:48 29 Oct '09  
GeneralRe: GetListItems parameters? Pin
Junaid Raza
23:42 29 Oct '09  
GeneralsGetID isn't really getting the right ID, it just gets the last created one... Pin
JakeRyan
11:05 24 Sep '09  
QuestionReverse of your post. :-) display Document Library to gridview/datagrid Pin
abhinay.potluri
16:50 15 Sep '09  
QuestionHow to access local drive files through Sharepoint Pin
rekhareddyp
0:31 29 Jun '09  
AnswerRe: How to access local drive files through Sharepoint Pin
Junaid Raza
0:38 29 Jun '09  
GeneralRe: How to access local drive files through Sharepoint Pin
rekhareddyp
1:09 29 Jun '09  
QuestionStruggling Pin
Steven Amani
5:25 28 May '09  
AnswerRe: Struggling Pin
Junaid Raza
6:13 28 May '09  
GeneralRe: Struggling Pin
Steven Amani
6:21 28 May '09  
GeneralRe: Struggling Pin
Junaid Raza
6:49 28 May '09  
GeneralHow to get the value in 'TestCol' column using GetListItems? Pin
kmb89
18:23 6 May '09  
QuestionHow to get the 'TestCol' with caml? Pin
kmb89
23:55 5 May '09  
AnswerRe: How to get the 'TestCol' with caml? Pin
Junaid Raza
1:08 6 May '09  
QuestionThe remote server returned an error: (409) Conflict. Pin
Manprit.bagga
21:33 8 Apr '09  
QuestionLIST item url Pin
manikandan23
0:21 26 Mar '09  
AnswerRe: LIST item url [modified] Pin
dsoutter
1:26 28 Jul '09  
Generalupdate business data column in document library Pin
Charu Agarwal
19:33 30 Sep '08  
QuestionAssistance with solution? Pin
treesprite
17:21 7 Jul '08  
GeneralHow to Rename a Folder copy folder or move folder Pin
T.Ashraf
8:48 18 Jun '08  
GeneralSpace in FileName or Document library Name Pin
Akthard
1:35 12 Jun '08  
GeneralRe: Space in FileName or Document library Name Pin
Junaid Raza
1:37 12 Jun '08  
GeneralRe: Space in FileName or Document library Name [modified] Pin
dsoutter
19:47 27 Jul '09  
Generaluploading search text Pin
Troy Lee
5:28 11 Jun '08  
GeneralHow to use only Web Service for this Update [modified] Pin
Akthard
3:45 10 Jun '08  


Last Updated 10 Jun 2008 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2009