公司尝试使用 SharePoint替代 FTP服务器存储文件

以下是 使用COMS 实现上传、下载、删除 文件 和 新增文件夹的功能

以下为 SharePoint操作类 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.SharePoint.Client;
using System.Security;
using System.Net;
using System.IO;

namespace SharePointIOTest.Class
{
    public class SharePointHelper
    {
        public string Host { get; set; }

        public string User { get; set; }

        public string Password { get; set; }

        public string Domain { get; set; }

        public string RootFolder { get; set; }

        public ClientContext clientContext { get; private set; }

        /// <summary>
        /// SharePointHelper
        /// </summary>
        /// <param name="strHost">Host</param>
        /// <param name="strUser">User</param>
        /// <param name="strPassword">Password</param>
        /// <param name="strRootFolder">根节点</param>
        /// <param name="strDomain">网域</param>
        public SharePointHelper(string strHost, string strUser, string strPassword, string strRootFolder, string strDomain = "dpbg")
        {
            Host = strHost;
            User = strUser;
            Password = strPassword;
            RootFolder = strRootFolder;
            Domain = strDomain;

            bindClientContext();
        }

        private void bindClientContext()
        {
            //这里使用的是网域账号验证,其他类型账号请自行实现
            clientContext = new ClientContext(Host);
            var password = new SecureString();
            Password.ToCharArray().ToList().ForEach(password.AppendChar);
            clientContext.Credentials = new NetworkCredential(User, password, Domain);
        }

        /// <summary>
        /// 创建文件夹
        /// </summary>
        /// <param name="strFloderPath">文件夹路径 示例:/RootFolder/OneLevel/SecondLevel</param>
        /// <returns></returns>
        public bool CreateFolder(string strFloderPath)
        {
            try
            {
                string folderNames = "/" + RootFolder;

                //无法创建根节点,所以发现 文件夹路径中存在根节点就trim掉
                strFloderPath = strFloderPath.TrimStart((folderNames + "/").ToCharArray());

                var list = clientContext.Web.Lists.GetByTitle(RootFolder);
                clientContext.Load(list);

                //一级级创建文件夹
                foreach (string folderName in strFloderPath.Split('/'))
                {
                    if (folderName != "")
                    {
                        folderNames += "/" + folderName;

                        //因为重复创建文件夹并不会报错,所以无需判断文件夹是否存在
                        list.RootFolder.Folders.Add(folderNames);

                        clientContext.ExecuteQuery();
                    }
                }
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="strFileName">文件名称 示例:A.xls</param>
        /// <param name="strFilePath">文件放置路径 示例:/RootFolder/OneLevel/SecondLevel</param>
        /// <param name="streamFileContent">文件内容</param>
        /// <returns></returns>
        public bool PushFile(string strFileName, string strFilePath, Stream streamFileContent)
        {
            try
            {
                var folder = clientContext.Web.GetFolderByServerRelativeUrl(strFilePath);
                clientContext.Load(folder);
                clientContext.ExecuteQuery();
                var fileUrl = String.Format("{0}/{1}", strFilePath, strFileName);
                Microsoft.SharePoint.Client.File.SaveBinaryDirect(clientContext, fileUrl, streamFileContent, true);
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="strFileName">文件名称 示例:A.xls</param>
        /// <param name="strFilePath">文件放置路径 示例:/RootFolder/OneLevel/SecondLevel</param>
        /// <param name="streamFileContent">文件内容</param>
        /// <returns></returns>
        public bool DownloadFile(string strFileName, string strFilePath, out Stream streamFileContent)
        {
            return DownloadFile(String.Format("{0}/{1}", strFilePath, strFileName), out streamFileContent);
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="strFileUrl">文件Url 示例:/RootFolder/OneLevel/SecondLevel/A.xls</param>
        /// <param name="streamFileContent">文件内容</param>
        /// <returns></returns>
        public bool DownloadFile(string strFileUrl, out Stream streamFileContent)
        {
            try
            {
                Microsoft.SharePoint.Client.File file = clientContext.Web.GetFileByServerRelativeUrl(strFileUrl);
                clientContext.Load(file);
                clientContext.ExecuteQuery();
                FileInformation fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(clientContext, strFileUrl);
                streamFileContent = fileInfo.Stream;
                return true;
            }
            catch
            {
                streamFileContent = null;
                return false;
            }
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="strFileName">文件名称 示例:A.xls</param>
        /// <param name="strFilePath">文件放置路径 示例:/RootFolder/OneLevel/SecondLevel</param>
        /// <returns></returns>
        public bool DeleteFile(string strFileName, string strFilePath)
        {
            return DeleteFile(String.Format("{0}/{1}", strFilePath, strFileName));
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="strFileUrl">文件Url 示例:/RootFolder/OneLevel/SecondLevel/A.xls</param>
        /// <returns></returns>
        public bool DeleteFile(string strFileUrl)
        {
            try
            {
                Microsoft.SharePoint.Client.File file = clientContext.Web.GetFileByServerRelativeUrl(strFileUrl);
                clientContext.Load(file);
                file.DeleteObject();
                clientContext.ExecuteQuery();

                return true;
            }
            catch
            {
                return false;
            }
        }
    }
}

下边为WebForm调用示例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Client;
using System.Net;
using System.Security;
using System.IO;
using SharePointIOTest.Class;

namespace SharePointIOTest
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        SharePointHelper sp = new SharePointHelper("SharePointSite", "user", "pwd", "rootFolder");
        protected void Page_Load(object sender, EventArgs e)
        {
        }
        
        //上传
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            var file = this.file1.PostedFile;
            lblMsg.Text = sp.PushFile(file.FileName, txtPath.Value, file.InputStream).ToString();
            txtFileName.Value = file.FileName;
        }
        
        //下载
        protected void btnExport_Click(object sender, EventArgs e)
        {
            Stream stream;
            lblMsg.Text = sp.DownloadFile(txtFileName.Value, txtPath.Value, out stream).ToString();
            using (var fileStream = new System.IO.FileStream(@"d:\downloads\" + txtPath.Value.Replace("/", "-") + "-" + txtFileName.Value, System.IO.FileMode.Create))
            {
                stream.CopyTo(fileStream);
            }

        }

        //创建文件夹
        protected void btnCreate_Click(object sender, EventArgs e)
        {
            lblMsg.Text = sp.CreateFolder(txtPath.Value).ToString();
        }
    }
}

下边是前端控件

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="SharePointIOTest.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <input type="text" id="txtPath" runat="server" title="Path" />
            <asp:Button ID="btnCreate" runat="server" OnClick="btnCreate_Click" Text="创建" />
            <br />
            <input type="file" id="file1" runat="server" />
            <asp:Button ID="btnSubmit" runat="server" OnClick="btnSubmit_Click" Text="上传" />
            <br />
            <input type="text" id="txtFileName" runat="server" title="FileName" />
            <asp:Button ID="btnExport" runat="server" OnClick="btnExport_Click" Text="下载" />
            <br />
            <asp:Label ID="lblMsg" runat="server"></asp:Label>

        </div>
    </form>
</body>
</html>

备注应该挺全的我就不多废话了

 

如果你有更多的问题,我建议你在这个地方寻找答案:https://sharepoint.stackexchange.com/