0

0

C#访问远程主机资源的多种方法分享

Y2J

Y2J

发布时间:2017-04-25 09:55:42

|

2495人浏览过

|

来源于php中文网

原创

最近要实现访问远程主机的共享目录中的一个文件。遇到了权限问题。google了一下,找到了几种解决方法,记录如下:
一、调用net use命令

 // 使用方法:
        //if (Connect("192.168.1.48", "用户名", "密码"))   
        //{
        //    File.Copy(@"\\192.168.1.48\共享目录\test.txt",   @"e:\\test.txt",   true);   
        //}
        public bool Connect(string remoteHost, string userName, string passWord)
        {
            bool Flag = true;
            Process proc = new Process();
            proc.StartInfo.FileName = "cmd.exe";
            proc.StartInfo.UseShellExecute = false;
            proc.StartInfo.RedirectStandardInput = true;
            proc.StartInfo.RedirectStandardOutput = true;
            proc.StartInfo.RedirectStandardError = true;
            proc.StartInfo.CreateNoWindow = true;
            try
            {
                proc.Start();
                string command = @"net  use  \\" + remoteHost + "  " + passWord + "  " + "  /user:" + userName + ">NUL";
                proc.StandardInput.WriteLine(command);
                command = "exit";
                proc.StandardInput.WriteLine(command);
                while (proc.HasExited == false)
                {
                    proc.WaitForExit(1000);
                }
                string errormsg = proc.StandardError.ReadToEnd();
                if (errormsg != "")
                    Flag = false;
                proc.StandardError.Close();
            }
            catch (Exception ex)
            {
                Flag = false;
            }
            finally
            {
                proc.Close();
                proc.Dispose();
            }
            return Flag;
        }

二、调用WNetAddConnection2、WNetAddConnection3或者NetUseAdd函数,进行磁盘映射。

using System;using System.Collections.Generic;using System.Text;       using System.Runtime.InteropServices;
namespace WindowsApplication1{    public class MyMap    {        [DllImport("mpr.dll", EntryPoint = "WNetAddConnection2")]        public static extern uint WNetAddConnection2(            [In] NETRESOURCE lpNetResource,            string lpPassword,            string lpUsername,            uint dwFlags);                [DllImport("Mpr.dll")]        public static extern uint WNetCancelConnection2(            string lpName,            uint dwFlags,            bool fForce);                [StructLayout(LayoutKind.Sequential)]        public class NETRESOURCE        {            public int dwScope;            public int dwType;            public int dwDisplayType;            public int dwUsage;            public string LocalName;            public string RemoteName;            public string Comment;            public string Provider;        }
        // remoteNetworkPath format:  @"\\192.168.1.48\sharefolder"        // localDriveName format:     @"E:"        public static bool CreateMap(string userName, string password, string remoteNetworkPath, string localDriveName)        {                        NETRESOURCE myNetResource = new NETRESOURCE();            myNetResource.dwScope = 2;       //2:RESOURCE_GLOBALNET            myNetResource.dwType = 1;        //1:RESOURCETYPE_ANY            myNetResource.dwDisplayType = 3; //3:RESOURCEDISPLAYTYPE_GENERIC            myNetResource.dwUsage = 1;       //1: RESOURCEUSAGE_CONNECTABLE            myNetResource.LocalName = localDriveName;            myNetResource.RemoteName = remoteNetworkPath;            myNetResource.Provider = null;
            uint nret = WNetAddConnection2(myNetResource, password, userName, 0);
            if (nret == 0)                return true;            else                return false;        }
        // localDriveName format:     @"E:"        public static bool DeleteMap(string localDriveName)        {            uint nret = WNetCancelConnection2(localDriveName, 1, true);
            if (nret == 0)                return true;            else                return false;        }
        public void test()        {            // 注意:            // remote、local、username的格式一定要正确,否则可能出现错误            string remote = @"\\192.168.1.48\generals";            string local = @"P:";            string username = @"Domain\UserName";            string password = @"Password";            bool ret = MyMap.CreateMap(username, password, remote, local);            if (ret)            {                //do what you want:                // ...                //File.Copy("q:\\test.htm", "c:\\test.htm");
                MyMap.DeleteMap(local);            }        }    }}

三、使用WebClient类

由于WebClient类可以上传下载文件,并且支持以http:、https:和file:开头的URI,所以可以用WebClient类来传输文件。
添加System.Net命名空间后使用如下代码下载文件:

private void Test1()        {            try            {                WebClient client = new WebClient();                NetworkCredential cred = new NetworkCredential("username", "password", "172.16.0.222");                client.Credentials = cred;                client.DownloadFile("file://172.16.0.222/test/111.txt", "111.txt");            }            catch (Exception ex)            {                // 如果网络很慢,而文件又很大,这时可能有超时异常(Time out)。            }        }
        public void Test2()        {            try            {                WebClient client = new WebClient();                NetworkCredential cred = new NetworkCredential("username", "password", "domain");                client.Credentials = cred;                client.DownloadFile("file://172.16.0.222/test/111.txt", "111.txt");            }            catch (Exception ex)            {                // 如果网络很慢,而文件又很大,这时可能有超时异常(Time out)。            }        }

类似的还可以试试WebRequest、FileWebRequest等:

 WebRequest req = WebRequest.Create("file://138.12.12.14/generals/test.htm");
                NetworkCredential cred = new NetworkCredential("username", "password", "IP");
                req.Credentials = cred;
                WebResponse response = req.GetResponse();
                Stream strm = response.GetResponseStream();
                StreamReader r = new StreamReader(strm);
                ... ...

四、角色模拟

/// 
    /// 身份模拟实现远程资源访问
    /// 
    public class FileImpersonation
    {
        // 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;
        [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern int LogonUser(string lpszUserName,
            string lpszDomain,
            string lpszPassword,
            int dwLogonType,
            int dwLogonProvider,
            ref IntPtr phToken);
        [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern int DuplicateToken(IntPtr hToken,
            int impersonationLevel,
            ref IntPtr hNewToken);
        [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern bool RevertToSelf();
        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        public static extern bool CloseHandle(IntPtr handle);
        private WindowsImpersonationContext impersonationContext;
        /// 
        /// 身份模拟
        /// 
        /// 独立服务器用IP,域环境就用域名
        /// 
        /// 
        /// 
        public bool impersonateValidUser(string userName, string domain, string password)
        {
            WindowsIdentity tempWindowsIdentity;
            IntPtr token = IntPtr.Zero;
            IntPtr tokenDuplicate = IntPtr.Zero;
            if (RevertToSelf())
            {
                // 这里使用LOGON32_LOGON_NEW_CREDENTIALS来访问远程资源。
                // 如果要(通过模拟用户获得权限)实现服务器程序,访问本地授权数据库可
                // 以用LOGON32_LOGON_INTERACTIVE
                if (LogonUser(userName, domain, password, LOGON32_LOGON_NEW_CREDENTIALS,
                    LOGON32_PROVIDER_DEFAULT, ref token) != 0)
                {
                    if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
                    {
                        tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
                        impersonationContext = tempWindowsIdentity.Impersonate();
                        if (impersonationContext != null)
                        {
                            AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
                            IPrincipal pr = System.Threading.Thread.CurrentPrincipal;
                            IIdentity id = pr.Identity;
                            CloseHandle(token);
                            CloseHandle(tokenDuplicate);
                            return true;
                        }
                    }
                }
            }
            if (token != IntPtr.Zero)
                CloseHandle(token);
            if (tokenDuplicate != IntPtr.Zero)
                CloseHandle(tokenDuplicate);
            return false;
        }
        /// 
        /// 取消模拟身份
        /// 
        public void undoImpersonation()
        {
            impersonationContext.Undo();
        }
        /// 
        /// 
        /// 
        /// 独立服务器用IP,域环境就用域名
        /// 
        /// 
        /// 需要执行的操作
        public void ImpersonateFunc(string username, string domain, string password, Action act)
        {
            bool isImpersonated = false;
            try
            {
                if (impersonateValidUser(username, domain, password))
                {
                    isImpersonated = true;
                    //File.Copy(@"\\192.168.1.48\generals\now.htm", "c:\\now.htm", true);
                    act();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            finally
            {
                if (isImpersonated)
                    undoImpersonation();
            }
        }
        //
    }
 FileImpersonation imp = new FileImpersonation();
            imp.ImpersonateFunc("Administrator", "192.168.0.125", "xxxx", () =>
            {
                var source = new DirectoryInfo(@"D:\HR");
                string targetFolder = @"\\192.168.0.125\d$\HR";
                if (!Directory.Exists(targetFolder))
                {
                    Directory.CreateDirectory(targetFolder);
                }
                foreach (FileInfo item in source.GetFiles())
                {
                    string targertFile = Path.Combine(targetFolder, item.Name);
                    File.Copy(item.FullName, targertFile, true);
                }
            });

五、比较

方法一通过调用Shell命令Net Use实现,有点笨拙。
方法二和方法一有些相似之处。映射远程资源,然后访问。
方法三由于会有超时异常出现,所以在网络速度快、传输小文件时是可以的。
方法四通过身份模拟实现远程资源访问。一些服务器进程就是通过这种方式运行的。这种方法也是我的最爱。

六、要注意的地方

关于这几种方法,google后都可以找到一些文章。但是等到自己实际测试时,有时会出现各种小错误,
这些错误基本来源于两方面:

1、函数的参数选择有问题,和自己的环境不相符。
比如        

英特尔AI工具
英特尔AI工具

英特尔AI与机器学习解决方案

下载
public static extern int LogonUser(String lpszUserName,
            String lpszDomain,
            String lpszPassword,
            int dwLogonType,
            int dwLogonProvider,
            ref IntPtr phToken);

中的dwLogonType,要访问远程资源就要用LOGON32_LOGON_NEW_CREDENTIALS,
要模拟本机用户就要用LOGON32_LOGON_INTERACTIVE。

2、函数的参数格式有问题。
    a、比如

 public static extern int LogonUser(String lpszUserName,
            String lpszDomain,
            String lpszPassword,
            int dwLogonType,
            int dwLogonProvider,
            ref IntPtr phToken);

    中的lpszUserName、lpszDomain、lpszPassword就要写清楚。

    我就在这遇到过问题,第一次测试时,远程服务器就是一台独立的文件服务器,这是我的调用方式:
        LogonUser("myname", "192.168.1.48", "password", LOGON32_LOGON_NEW_CREDENTIALS,
                    LOGON32_PROVIDER_DEFAULT, ref token);

    第二次测试时,远程服务器是域MyDomain中的一个成员服务器,提供文件服务。这时代码就应该是:

 LogonUser("myname", "MyDomain", "password", LOGON32_LOGON_NEW_CREDENTIALS,
                    LOGON32_PROVIDER_DEFAULT, ref token);

    注意,代码中是MyDomain而不是IP地址。

    b、再如:
    参考上面代码

 string remote = @"\\192.168.1.48\generals";
            string local = @"P:";
            string username = @"Domain\UserName";
            string password = @"Password";

    如果@"\\192.168.1.48\generals"变成@"\\192.168.1.48\generals\”就会出错;
    如果是域中的用户,那么把@"Domain\UserName"变成@"UserName"就会出错。

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

通义千问
通义千问

阿里巴巴推出的全能AI助手

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
C++ 设计模式与软件架构
C++ 设计模式与软件架构

本专题深入讲解 C++ 中的常见设计模式与架构优化,包括单例模式、工厂模式、观察者模式、策略模式、命令模式等,结合实际案例展示如何在 C++ 项目中应用这些模式提升代码可维护性与扩展性。通过案例分析,帮助开发者掌握 如何运用设计模式构建高质量的软件架构,提升系统的灵活性与可扩展性。

14

2026.01.30

c++ 字符串格式化
c++ 字符串格式化

本专题整合了c++字符串格式化用法、输出技巧、实践等等内容,阅读专题下面的文章了解更多详细内容。

9

2026.01.30

java 字符串格式化
java 字符串格式化

本专题整合了java如何进行字符串格式化相关教程、使用解析、方法详解等等内容。阅读专题下面的文章了解更多详细教程。

12

2026.01.30

python 字符串格式化
python 字符串格式化

本专题整合了python字符串格式化教程、实践、方法、进阶等等相关内容,阅读专题下面的文章了解更多详细操作。

4

2026.01.30

java入门学习合集
java入门学习合集

本专题整合了java入门学习指南、初学者项目实战、入门到精通等等内容,阅读专题下面的文章了解更多详细学习方法。

20

2026.01.29

java配置环境变量教程合集
java配置环境变量教程合集

本专题整合了java配置环境变量设置、步骤、安装jdk、避免冲突等等相关内容,阅读专题下面的文章了解更多详细操作。

18

2026.01.29

java成品学习网站推荐大全
java成品学习网站推荐大全

本专题整合了java成品网站、在线成品网站源码、源码入口等等相关内容,阅读专题下面的文章了解更多详细推荐内容。

19

2026.01.29

Java字符串处理使用教程合集
Java字符串处理使用教程合集

本专题整合了Java字符串截取、处理、使用、实战等等教程内容,阅读专题下面的文章了解详细操作教程。

3

2026.01.29

Java空对象相关教程合集
Java空对象相关教程合集

本专题整合了Java空对象相关教程,阅读专题下面的文章了解更多详细内容。

6

2026.01.29

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
C# 教程
C# 教程

共94课时 | 8万人学习

C 教程
C 教程

共75课时 | 4.3万人学习

C++教程
C++教程

共115课时 | 14.8万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号