sahrepoint 上传到文档库

时间:2021-06-22 20:57:15

sharepoint学习笔记汇总

http://blog.csdn.net/qq873113580/article/details/20390149

 

 

 

 

/// <summary>
        /// 上传附件到文档库(包含删除获取)
        /// </summary>
        /// <param name="dirName"></param>
        /// <param name="fileUpload"></param>
        /// <returns></returns>
        private string GetFileUrl(string dirName, FileUpload fileUpload)
        {
            string url = "";
            if (fileUpload.HasFile == false)
            {
                return url;
            }
            using (SPWeb rootWeb = new SPSite(Common.rootUrl).OpenWeb())
            {
                //找到文档库的位置
                SPList libList = rootWeb.GetList(Common.rootUrl + "/ReportFile/Forms/AllItems.aspx");
                //找到文档库根文件夹
                SPFolder rootFolder = libList.RootFolder;

                //子文件夹
                SPFolder subFolder = null;

                #region 不存在文件夹就新建
                bool exists = false;
                //根文件夹下的文件夹集合
                SPFolderCollection folders = rootFolder.SubFolders;
                foreach (SPFolder folde in folders)
                {
                    if (folde.Name == dirName)
                    {
                        exists = true;
                        break;
                    }
                }
                if (exists == false)
                {
                    //不存在就在根文件夹下加入一个文件夹
                    subFolder = rootFolder.SubFolders.Add(rootFolder.Url + "/" + dirName);
                }
                else
                {
                    //存在就直接读取这个文件夹
                    subFolder = rootFolder.SubFolders[dirName];
                }
                #endregion

 

                #region 删除子文件夹下的全部文件在加入
                SPFileCollection files = subFolder.Files;
               for (int i = files.Count - 1; i >= 0; i--)
                {
                    files[i].Delete();
                }
                #endregion
                //获取文件流
                Stream fStream = fileUpload.PostedFile.InputStream;
                byte[] contents = new byte[fStream.Length];
                fStream.Read(contents, 0, (int)fStream.Length);
                //保存到文档库
                subFolder.Files.Add(fileUpload.FileName, contents);
                fStream.Close();
                //获取上传之后的文件位置http://xxx/xx/xx.xx
                url = Common.rootUrl + "/" + subFolder.Url + "/" + fileUpload.FileName;
            }
            return url;
        }