Sharepoint – Dokument einer Dokumentenbibliothek hinzufügen

Hallo Leute,

heute möchte ich euch kurz zeigen, wie Ihr ein Dokument bzw. einen Stream in eine Dokumentenbibliothek hinzufügt.
Meine Methode fügt zudem eine fortlaufende Nummer hinzu, falls ein Dokument mit dem angegebenen Namen bereits existiert (Parameter „overwrite“).

        /// <summary>
        /// Checks if file exists.
        /// </summary>
        /// <param name="listName">Name of the list.</param>
        /// <param name="fileName">Name of the file.</param>
        /// <returns></returns>
        public static bool CheckIfFileExists(string listName, string fileName)
        {
            var web = SPContext.Current.Web;
            var docUrl = Path.Combine(web.Url, listName, fileName);

            SPFile file = web.GetFile(docUrl);
            return file.Exists;
        }



        /// <summary>
        /// Adds the file to list.
        /// </summary>
        /// <param name="listName">Name of the list.</param>
        /// <param name="fileName">Name of the file.</param>
        /// <param name="streamToSave">The stream to save.</param>
        /// <param name="overwrite">if set to <c>true</c> [overwrite].</param>
        /// <exception cref="System.Exception">Cannot add file stream to list. Following error occured:  + ex.Message</exception>
        public static void AddFileToList(string listName, string fileName, Stream streamToSave, bool overwrite = false)
        {
            try
            {
                var fileNameToUse = string.Format(fileName, "");
                var web = SPContext.Current.Web;

                if (!overwrite)
                {
                    for(int i = 1; i <= 100; i++)
                    {
                        if (CheckIfFileExists(listName, fileNameToUse))
                        {
                            fileNameToUse = string.Format(fileName, " (" + i + ")");
                        }
                        else
                            break;
                    }
                }

                var docUrl = Path.Combine(web.Url, listName, fileNameToUse);
                web.Files.Add(docUrl, streamToSave);
            }
            catch (Exception ex)
            {
                throw new Exception("Cannot add file stream to list. Following error occured: " + ex.Message, ex);
            }
            
        }

Beispiel:

AddFileToList(this.DocLibrary, "Protokoll {0}.docx", stream, false);
// or
AddFileToList(this.DocLibrary, "Protokoll {0}.docx", stream);

Cheers,
Chris

Leave a reply