模拟账户跨服务器上传下载共享文件

来源:互联网 发布:第一届大数据教育论坛 编辑:程序博客网 时间:2024/04/30 13:05
using System;using System.Collections.Generic;using System.Text;using System.Diagnostics;using System.Runtime.InteropServices;using System.Security.Principal;using System.IO;using System.Drawing;namespace CommLib{    public class ShareFolder    {        [DllImport("advapi32.dll", SetLastError = true)]        private static extern bool LogonUser(string        lpszUsername, string lpszDomain, string lpszPassword,        int dwLogonType, int dwLogonProvider, ref IntPtr phToken);        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]        private static extern bool CloseHandle(IntPtr handle);        [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]        public extern static bool DuplicateToken(IntPtr existingTokenHandle,        int SECURITY_IMPERSONATION_LEVEL, ref IntPtr duplicateTokenHandle);        // logon types        const int LOGON32_LOGON_INTERACTIVE = 2;        const int LOGON32_LOGON_NETWORK = 3;        const int LOGON32_LOGON_NEW_CREDENTIALS = 9;        // logon providers        const int LOGON32_PROVIDER_DEFAULT = 0;        const int LOGON32_PROVIDER_WINNT50 = 3;        const int LOGON32_PROVIDER_WINNT40 = 2;        const int LOGON32_PROVIDER_WINNT35 = 1;        static string ShareUserName = System.Configuration.ConfigurationManager.AppSettings["ShareUserName"];        static string ShareDomain = System.Configuration.ConfigurationManager.AppSettings["ShareDomain"];        static string SharePassword = System.Configuration.ConfigurationManager.AppSettings["SharePassword"];        static string SharePhotoPath = System.Configuration.ConfigurationManager.AppSettings["SharePhotoPath"];        static string HelpUserName = System.Configuration.ConfigurationManager.AppSettings["HelpUserName"];        static string HelpDomain = System.Configuration.ConfigurationManager.AppSettings["HelpDomain"];        static string HelpPassword = System.Configuration.ConfigurationManager.AppSettings["HelpPassword"];        static string HelpFilePath = System.Configuration.ConfigurationManager.AppSettings["HelpFilePath"];        /// <summary>        /// 上传照片到共享文件夹        /// </summary>        /// <param name="UploadPhotoBase64">照片Base64数据</param>        /// <returns>照片保存路径</returns>        public static string UploadSharePhotos(string UploadPhotoBase64)        {            string RemarkImages = "";//照片存放短路径            IntPtr tokenHandle = new IntPtr(0);            IntPtr dupeTokenHandle = new IntPtr(0);            tokenHandle = IntPtr.Zero;            bool returnValue = LogonUser(ShareUserName, ShareDomain, SharePassword, LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_DEFAULT, ref tokenHandle);            if (returnValue == false)            {                int ret = Marshal.GetLastWin32Error();                throw new System.ComponentModel.Win32Exception(ret);            }            WindowsIdentity newId = null;            WindowsImpersonationContext impersonatedUser = null;            using (newId = new WindowsIdentity(tokenHandle))            {                using (impersonatedUser = newId.Impersonate())                {//操作文档                    string[] UploadPhotos = UploadPhotoBase64.Split('|');                    string folderDate = DateTime.Now.ToString("yyyy_MM_dd");                    string fullfileFolder = SharePhotoPath + "\\" + folderDate;                    if (System.IO.Directory.Exists(fullfileFolder) == false)//如果不存在就创建文件夹                    {                        System.IO.Directory.CreateDirectory(fullfileFolder);                    }                    foreach (string ImagesBase in UploadPhotos)                    {                        byte[] imageBytes = Convert.FromBase64String(ImagesBase);                        string fileName = DateTime.Now.ToString("yyyy_MM_dd_hh_mm_ss_ffffff") + ".jpeg";                        string filePath = fullfileFolder + "\\" + fileName;                        FileStream ms = new FileStream(filePath, FileMode.Create);                        ms.Write(imageBytes, 0, imageBytes.Length);                        ms.Flush();                        ms.Close();                        RemarkImages += folderDate + "\\" + fileName + "|";//记录文件路径                    }                    if (RemarkImages.Length > 0)                    {                        RemarkImages = RemarkImages.Substring(0, RemarkImages.Length - 1);//去除尾部分隔符 |                    }                }            }            impersonatedUser.Undo();            if (tokenHandle != IntPtr.Zero)                CloseHandle(tokenHandle);            return RemarkImages;        }        /// <summary>        /// 从共享文件夹读取图片数据信息        /// </summary>        /// <param name="PhotoPath"></param>        /// <returns></returns>        public static MemoryStream GetSharePhoto(string PhotoPath)        {            System.IO.MemoryStream ms = new System.IO.MemoryStream();//照片数据流            IntPtr tokenHandle = new IntPtr(0);            IntPtr dupeTokenHandle = new IntPtr(0);            tokenHandle = IntPtr.Zero;            bool returnValue = LogonUser(ShareUserName, ShareDomain, SharePassword, LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_DEFAULT, ref tokenHandle);            if (returnValue == false)            {                int ret = Marshal.GetLastWin32Error();                throw new System.ComponentModel.Win32Exception(ret);            }            WindowsIdentity newId = null;            WindowsImpersonationContext impersonatedUser = null;            using (newId = new WindowsIdentity(tokenHandle))            {                using (impersonatedUser = newId.Impersonate())                {//操作文档                    string fileFolder = System.Configuration.ConfigurationManager.AppSettings["SharePhotoPath"];                    string filePath = fileFolder + "\\" + PhotoPath;//图片存放路径                    if (System.IO.File.Exists(filePath))                    {                        Image Photo = Image.FromFile(filePath);                        Photo.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);                        Photo.Dispose();                    }                }            }            impersonatedUser.Undo();            if (tokenHandle != IntPtr.Zero)                CloseHandle(tokenHandle);            return ms;        }        public static byte[] GetFile(string DownFileName)        {            byte[] DownloadFile = null;//要下载的文件的数据            IntPtr tokenHandle = new IntPtr(0);            IntPtr dupeTokenHandle = new IntPtr(0);            tokenHandle = IntPtr.Zero;            bool returnValue = LogonUser(HelpUserName, HelpDomain, HelpPassword, LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_DEFAULT, ref tokenHandle);            if (returnValue == false)            {                int ret = Marshal.GetLastWin32Error();                throw new System.ComponentModel.Win32Exception(ret);            }            WindowsIdentity newId = null;            WindowsImpersonationContext impersonatedUser = null;            using (newId = new WindowsIdentity(tokenHandle))            {                using (impersonatedUser = newId.Impersonate())                {//操作文档                    string filePath = HelpFilePath + "\\" + DownFileName;//图片存放路径                    DownloadFile = File.ReadAllBytes(filePath);//获取文件数据                }            }            impersonatedUser.Undo();            if (tokenHandle != IntPtr.Zero)                CloseHandle(tokenHandle);            return DownloadFile;        }    }}web.config  <appSettings>    <add key="SharePhotoPath" value="\\VMXP\Test"/>    <add key="ShareUserName" value="Guest"/>    <add key="SharePassword" value="123456"/>    <add key="ShareDomain" value="VMXP"/>    <add key="HelpFilePath" value="\\VMXP\Test"/>    <add key="HelpUserName" value="Guest"/>    <add key="HelpPassword" value="123456"/>    <add key="HelpDomain" value="VMXP"/>  </appSettings>

原创粉丝点击