Share Point Server Accessing

Simplest way to Upload a document to sharepoint using web services


Using following web service URL(s) will help you.

1.  http://www.yourSPserverDomain/_vti_bin/Lists.asmx
2.  http://www.yourSPserverDomain/_vti_bin/Copy.asmx

And also The SharePoint Server have more then 25 web services available for accessing the SharePoint Server. For Eg: Create Folder , Upload Files , Modifying file/Folder Name and remove file/folder and also have lot of functionality.

Below coding will help you for uploading files to your existing or New folder in the SharePoint Server.


 public class SPAccess
    {
        Lists m_listService;
        ICredentials m_credentials;
        ListInfoCollection m_lists;

        public SPAccess()
        {
            m_credentials = GetCredentials(); //CredentialCache.DefaultCredentials;
            m_listService = new Lists();
            m_listService.Credentials = m_credentials;
            m_lists = new ListInfoCollection(m_listService);
        }

        private ICredentials GetCredentials()
        {
            return new NetworkCredential(ConfigurationManager.AppSettings["SPWSUsername"], ConfigurationManager.AppSettings["SPWSUserPassword"], ConfigurationManager.AppSettings["SPWSDomain"]);
        }

        public class ListInfo
        {
            public string m_rootFolder;
            public string m_listName;
            public string m_version;
            public string m_webUrl;
            public ListInfo(XmlNode listResponse)
            {
                m_rootFolder = listResponse.Attributes["RootFolder"].Value + "/";
                m_listName = listResponse.Attributes["ID"].Value;
                m_version = listResponse.Attributes["Version"].Value;
            }
            public bool IsMatch(string url)
            {
                try
                {
                    url += "/";
                    return url.Substring(0, m_rootFolder.Length) == m_rootFolder;
                }
                catch { }
                return false;
            }
        }

        public class ListInfoCollection : IEnumerable
        {

            Lists m_listService;
            Dictionary m_lists = new Dictionary();

            public ListInfoCollection(Lists listService)
            {
                m_listService = listService;
            }

            public IEnumerator GetEnumerator()
            {
                return m_lists.Values.GetEnumerator();
            }

            IEnumerator IEnumerable.GetEnumerator()
            {
                return this.GetEnumerator();
            }

            public ListInfo Find(FileInfo fileInfo)
            {
                if (m_lists.ContainsKey(fileInfo.LookupName))
                    return m_lists[fileInfo.LookupName];
                foreach (ListInfo li in m_lists.Values)
                    if (li.IsMatch(fileInfo.LookupName)) return li;
                string webUrl = fileInfo.m_URL;
                if (fileInfo.m_listInfo != null && !string.IsNullOrEmpty(fileInfo.m_listInfo.m_listName))
                {
                    ListInfo listInfo = new ListInfo(CallService(ref webUrl, delegate { return m_listService.GetList(fileInfo.LookupName); }));
                    listInfo.m_webUrl = webUrl;
                    return listInfo;
                }
                else
                {
                    XmlNode lists = CallService(ref webUrl, delegate { return m_listService.GetListCollection(); });
                    if (lists == null) throw new Exception("Could not find web.");
                    //Find list by RootFolder (which doesn't seem to be populated in GetListCollection response so must iterate GetList response)
                    foreach (XmlNode list in lists.ChildNodes)
                    {
                        ListInfo listInfo = new ListInfo(m_listService.GetList(list.Attributes["Name"].Value));
                        listInfo.m_webUrl = webUrl;
                        m_lists.Add(listInfo.m_listName, listInfo);
                        if (listInfo.IsMatch(fileInfo.LookupName))
                            return listInfo;
                    }
                }
                throw new Exception("Could not find list.");
            }
            private delegate XmlNode ServiceOperation();
            private XmlNode CallService(ref string webURL, ServiceOperation serviceOperation)
            {
                try
                {
                    webURL = ConfigurationManager.AppSettings["UrlListSite"].Trim();   //"http://us-zetadocs.idec.local";  // webURL.Substring(0, webURL.LastIndexOf("/"));
                    try
                    {
                        m_listService.Url = webURL + "/_vti_bin/Lists.asmx";
                        return serviceOperation();
                    }
                    catch
                    {
                        return CallService(ref webURL, serviceOperation);
                    }
                }
                catch
                {
                    webURL = null;
                    return null;
                }
            }
        }

        public class FileInfo
        {
            public string m_URL;
            public byte[] m_bytes;
            public Dictionary m_properties;
            public ListInfo m_listInfo;
            public bool m_ensureFolders = true;
            private Uri m_uri;
            public bool HasProperties
            {
                get { return m_properties != null && m_properties.Count > 0; }
            }
            public string RelativeFilePath
            {
                get { return m_URL.Substring(m_URL.IndexOf(m_listInfo.m_rootFolder) + 1); }
            }
            public Uri URI
            {
                get
                {
                    if (m_uri == null) m_uri = new Uri(m_URL);
                    return m_uri;
                }
            }
            public string LookupName
            {
                get
                {
                    if (m_listInfo != null && !string.IsNullOrEmpty(m_listInfo.m_listName))
                        return m_listInfo.m_listName;
                    return URI.LocalPath;
                }
            }
            public FileInfo(string url, byte[] bytes, Dictionary properties)
            {
                m_URL = url.Replace("%20", " ");
                m_bytes = bytes;
                m_properties = properties;
            }
        }

        // Calling method
        public bool Upload(string folderName, string fileName, byte[] bytes, Dictionary properties)
        {
            StringBuilder destinationUrl = new StringBuilder();
            //Get SharePoint URL from Web.Config
            destinationUrl.Append(ConfigurationManager.AppSettings["UrlListSite"].Trim());
            //Get SharePoint Folder Name From Web.Config
            destinationUrl.Append(ConfigurationManager.AppSettings["SPSDCUploadFolder"].Trim());
            //Append Our Dynamic Folder and File Name to same URL
            destinationUrl.Append(folderName + "/" + fileName);
            int fileCount = 1;
            while (fileCount > 0)
            {
                if (!RemoteFileExists(string.Format(destinationUrl.ToString(), fileCount)))
                    break;
                else
                    fileCount++;
                if (fileCount > 20)
                    throw new Exception("File Checking Error: overlimit count:" + fileCount);
            }
            return Upload(new FileInfo(string.Format(destinationUrl.ToString(), fileCount), bytes, properties));
        }

        public bool Upload(FileInfo fileInfo)
        {
            if (fileInfo.HasProperties)
                fileInfo.m_listInfo = m_lists.Find(fileInfo);
            bool result = TryToUpload(fileInfo);
            if (!result && fileInfo.m_ensureFolders)
            {
                string root = fileInfo.URI.AbsoluteUri.Replace(fileInfo.URI.AbsolutePath, "");
                for (int i = 0; i < fileInfo.URI.Segments.Length - 1; i++)
                {
                    root += fileInfo.URI.Segments[i];
                    if (i > 1) CreateFolder(root);
                }
                result = TryToUpload(fileInfo);
            }
            return result;
        }

        private bool TryToUpload(FileInfo fileInfo)
        {
            try
            {
                WebRequest request = WebRequest.Create(fileInfo.m_URL);
                request.Credentials = m_credentials;
                // request.ContentType = "multipart/form-data; boundary=" + boundaryString;
                request.Method = "PUT";
                byte[] buffer = new byte[1024];
                using (Stream stream = request.GetRequestStream())
                using (MemoryStream ms = new MemoryStream(fileInfo.m_bytes))
                    for (int i = ms.Read(buffer, 0, buffer.Length); i > 0; i = ms.Read(buffer, 0, buffer.Length))
                        stream.Write(buffer, 0, i);
                WebResponse response = request.GetResponse();
                response.Close();
                return true;
            }
            catch (WebException)
            {
                return false;
            }
        }

        private bool CreateFolder(string folderURL)
        {
            try
            {
                WebRequest request = WebRequest.Create(folderURL);
                request.Credentials = m_credentials;
                request.Method = "MKCOL";
                WebResponse response = request.GetResponse();
                response.Close();
                return true;
            }
            catch (WebException)
            {
                return false;
            }
        }

        private bool RemoteFileExists(string url)
        {
            try
            {
                //Creating the HttpWebRequest
                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                request.Credentials = GetCredentials();
                //Setting the Request method HEAD, you can also use GET too.
                request.Method = "HEAD";
                //Getting the Web Response.
                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                //Returns TURE if the Status code == 200
                return (response.StatusCode == HttpStatusCode.OK);
            }
            catch
            {
                return false;
            }
        }
    }

------------------------------------------------------------------------
If you need more information about SP please go to following sites.

http://geek.hubkey.com/2007/10/upload-file-to-sharepoint-document.html

http://stackoverflow.com/questions/2147539/simplest-way-to-upload-a-document-to-sharepoint-using-web-services

Thanks. :)

No comments:

Post a Comment