0

I'm using an access database to generate a folder full of files. I want to copy the folder to sharepoint. I'm trying to do this by programmatically mapping the sharepoint library to a network drive, copying the folder and then disconnecting the drive. If the destination folder is empty, it all works perfectly. The issue is that the destination folder will never be empty, so all files will need to be overwritten. Enter the "check out" required issue. Is there a way to checkout/check-in each file as it's overwritten? I'd like to be able to maintain version history, will deleting all files and then copying the new ones keep the history? Is there a better way to do this. The files need to be generated outside SharePoint. Thanks.

Private Sub Copy_Folder()

  Dim FSO As Object
  Dim oFile As Object
  Dim FromPath As String
  Dim ToPath As String
  Dim strWhen As String

  FromPath = "C:\Files\Folder"

  If Right(FromPath, 1) = "\" Then
    FromPath = Left(FromPath, Len(FromPath) - 1)
  End If

  If Right(ToPath, 1) = "\" Then
    ToPath = Left(ToPath, Len(ToPath) - 1)
  End If

  Set objNetwork = CreateObject("Wscript.Network")
  objNetwork.MapNetworkDrive "G:", "\\sharepoint\site\folder"

  ToPath = "G:"

  Set FSO = CreateObject("scripting.filesystemobject")

  If FSO.FolderExists(FromPath) = False Then
    MsgBox FromPath & " doesn't exist"
    Exit Sub
  End If

  FSO.CopyFolder Source:=FromPath, Destination:=ToPath
  MsgBox "The folder has been copied"

  objNetwork.RemoveNetworkDrive "G:"

  Set FSO = Nothing

End Sub
0

Since you are using VBA, I can assume you can not use Server Side Object Model. So to upload file in the document library, Check out and Check In you need to use Lists.asmx and Copy.asmx WebService. I am not strong in VBA, so I am writing this code in C# console application. You can follow the way, it is working fine.

  1. Get the Reference of the Lists.asmx and Copy.asmx web service in your application
  2. Now the logic is:
Step 1: Check the uploadable file exist in the Document Library folder using lists.asmx or not
Step 1.1: If Yes, then Checkout the file using CheckOutFile function of Lists.asmx web service
Step 1.2: If No, Do Nothing
Step 2: Upload the file using Copy.asmx web service
Step 3: Check In the file using CheckInFile function of Lists.asmx web service

The code is as follows:


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplicationSP
{
    class Program
    {
        public static string SiteURL = "http://win-og78bueinb9/sites/hub";
        public static string DocumentLibrary = "Documents";
        public static string DestinationFolderPath = "http://win-og78bueinb9/sites/hub/Shared%20Documents/Folder1";
        public static string UserName = "Administrator";
        public static string Domain = "DOMAIN";
        public static string Password = "PASSWORD";
        public static string SourceFilePath = @"C:\Users\Administrator\Desktop\TestSudip.docx";
        /*
        // Example of parameters for this function

        //Parameter 
        string DestinationFolderPath =  + "/" +  + "/" +  
                                         + "/" + ;
        //Example
        string DestinationFolderPath = "http://sharepoint.infoyen.com" + "/" + "HistoricalDocs"  
                                         + "/" + "Historical" + "/" + "IT";

        //Parameter 3
        string sourceFilePath = "c:\HistoricalDocs\Historical\20121111\IT\Historical_IT.doc;
        */
        static void Main(string[] args)
        {
            //Check the file exist or not in th Folder
            string queryXml = "" + Path.GetFileName(SourceFilePath) + "";
            string itemId = GetItemID(DocumentLibrary, queryXml, DestinationFolderPath);
            //If the file does not exist then upload the file.
            if (!itemId.Equals(string.Empty))
            {
                CheckOut(DestinationFolderPath + "/" + Path.GetFileName(SourceFilePath));
            }
            UploadFile(DestinationFolderPath + "/" + Path.GetFileName(SourceFilePath), DestinationFolderPath, SourceFilePath);
            CheckIn(DestinationFolderPath + "/" + Path.GetFileName(SourceFilePath));

        }
        public static void CheckOut(string destinationPath)
        {
            Lists listReference = new Lists(SiteURL);
            string lookupId = string.Empty;
            try
            {
                listReference.Credentials = new NetworkCredential(UserName, Password, Domain);
                listReference.CheckOutFile(destinationPath, "False", string.Empty);
            }
            catch (Exception ex)
            {
                //exception
            }
            finally
            {
                if (listReference != null)
                    listReference.Dispose();
            }
        }
        public static void CheckIn(string destinationPath)
        {
            Lists listReference = new Lists(SiteURL);
            string lookupId = string.Empty;
            try
            {
                listReference.Credentials = new NetworkCredential(UserName, Password, Domain);
                listReference.CheckInFile(destinationPath, string.Empty, "0");
            }
            catch (Exception ex)
            {
                //exception
            }
            finally
            {
                if (listReference != null)
                    listReference.Dispose();
            }
        }
        public static string GetItemID(string strListName, string queryXml, string destinationFolderPath)
        {
            Lists listReference = new Lists(SiteURL);
            string lookupId = string.Empty;
            try
            {
                listReference.Credentials = new NetworkCredential(UserName, Password, Domain);
                System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
                System.Xml.XmlElement query = xmlDoc.CreateElement("Query");
                System.Xml.XmlElement viewFields = xmlDoc.CreateElement("ViewFields");
                System.Xml.XmlElement queryOptions = xmlDoc.CreateElement("QueryOptions");
                query.InnerXml = queryXml;
                viewFields.InnerXml = "";
                queryOptions.InnerXml = "" + destinationFolderPath + "";
                System.Xml.XmlNode items;
                if (String.IsNullOrEmpty(destinationFolderPath))
                    items = listReference.GetListItems(strListName, string.Empty, query, viewFields, string.Empty, null, null);
                else
                    items = listReference.GetListItems(strListName, string.Empty, query, viewFields, string.Empty, queryOptions, null);

                foreach (System.Xml.XmlNode node in items)
                {
                    if (node.Name == "rs:data")
                    {
                        for (int i = 0; i < node.ChildNodes.Count; i++)
                        {
                            if (node.ChildNodes[i].Name == "z:row")
                            {
                                lookupId = node.ChildNodes[i].Attributes["ows_ID"].Value;
                                break;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //exception
            }
            finally
            {
                if (listReference != null)
                    listReference.Dispose();
            }

            return lookupId;
        }
        private static byte[] GetFileFromFileSystem(string path)
        {
            byte[] fileBytes = null;

            if (File.Exists(path))
            {
                //read the file.
                using (FileStream fs = File.Open(path, FileMode.Open))
                {
                    fileBytes = new byte[fs.Length];
                    fs.Position = 0;
                    fs.Read(fileBytes, 0, Convert.ToInt32(fs.Length));
                }
            }
            return fileBytes;
        }
        public static void UploadFile(string destinationPath, string destinationFolderPath, string sourceFilePath)
        {
            int result = -1; // -1 means failure
            Copy copyReference = new Copy(SiteURL);
            try
            {
                string destination = destinationPath;
                string[] destinationUrl = { destination };
                byte[] fileBytes = GetFileFromFileSystem(sourceFilePath);
                copyReference.Credentials = new NetworkCredential(UserName, Password, Domain);

                CopyResult[] cResultArray = null;

                FieldInformation titleField = new FieldInformation();
                titleField.DisplayName = "Title";
                titleField.Type = FieldType.Text;
                titleField.Value = Path.GetFileName(destinationPath);

                //Associate metadata
                FieldInformation[] filedInfo = { titleField };
                //Upload the document from Local to SharePoint
                copyReference.CopyIntoItems(destination, destinationUrl, filedInfo, fileBytes, out cResultArray);
            }
            catch (Exception ex)
            {//exception code here 
            }
            finally
            {
                if (copyReference != null)
                    copyReference.Dispose();
            }
        }
    }
}

Sorry for providing the solution in C#.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.