在要求输入邮箱的文本域,请填写真实的邮件地址。非真实邮件地址,将收不到回复信息。

.Net访问Windows共享目录

DotNet 清风 60℃ 0评论

背景

无意见又翻到了曾经的一些项目,看到了关于.Net访问Windows共享目录的一些代码。曾经在内网通过共享目录作为服务器文件的存储方式,个人觉得部分的实现代码可以记录下来作为备份。所以,整理了以下代码。

代码实现

公用内容


    /// <summary>
    ///  IdentityScope 的摘要说明
    /// </summary>
    public class IdentityScope : IDisposable
    {
        // obtains user token
        [DllImport("advapi32.dll", SetLastError = true)]
        static extern bool LogonUser(string pszUsername, string pszDomain, string pszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);

        // closes open handes returned by LogonUser

        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]

        extern static bool CloseHandle(IntPtr handle);


        [DllImport("Advapi32.DLL")]
        static extern bool ImpersonateLoggedOnUser(IntPtr hToken);

        [DllImport("Advapi32.DLL")]
        static extern bool RevertToSelf();

        // 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;

        private bool disposed;

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="sUsername">用户名</param>
        /// <param name="sDomain">第二个参数是域名,有域名的话写域名,没有域名写目标机器的IP·</param>
        /// <param name="sPassword">密码</param>
        public IdentityScope(string sUsername, string sDomain, string sPassword)
        {

            // initialize tokens
            IntPtr pExistingTokenHandle = new IntPtr(0);
            IntPtr pDuplicateTokenHandle = new IntPtr(0);
            try
            {

                // get handle to token
                bool bImpersonated = LogonUser(sUsername, sDomain, sPassword, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref pExistingTokenHandle);
                if (bImpersonated)
                {
                    if (!ImpersonateLoggedOnUser(pExistingTokenHandle))
                    {
                        int nErrorCode = Marshal.GetLastWin32Error();
                        // throw new Exception("ImpersonateLoggedOnUser error;Code=" + nErrorCode);
                        throw new Exception("文件服务器远程连接异常,请稍后再试!");
                    }

                }
                else
                {
                    int nErrorCode = Marshal.GetLastWin32Error();
                    //throw new Exception("LogonUser error;Code=" + nErrorCode);
                    throw new Exception("文件服务器远程连接异常,请稍后再试!");

                }

            }
            finally
            {
                // close handle(s)
                if (pExistingTokenHandle != IntPtr.Zero)
                {

                    CloseHandle(pExistingTokenHandle);
                }

                if (pDuplicateTokenHandle != IntPtr.Zero)
                {

                    CloseHandle(pDuplicateTokenHandle);
                }
            }

        }

        protected virtual void Dispose(bool disposing)
        {

            if (!disposed)
            {
                RevertToSelf();
                disposed = true;
            }

        }

        public void Dispose()
        {
            Dispose(true);
        }
    }

访问调用

      
using ShareAccess.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ShareAccess
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
               
                using (IdentityScope c = new IdentityScope("Administrator","192.168.0.102","1234567"))
                {
                    FileInfo fileInfo = new FileInfo("C:\\Users\\finder\\Desktop\\taskapp2.zip");
                    fileInfo.CopyTo("\\\\192.168.0.102\\Share\\" + fileInfo.Name);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"{ex}");
            }
            Console.Read();
        }
    }
}

示例下载

.Net访问Windows共享目录示例

转载请注明:清风博客 » .Net访问Windows共享目录

喜欢 (11)or分享 (0)
支付宝扫码打赏 微信打赏
发表我的评论
取消评论

CAPTCHA Image
Reload Image
表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址