Windows 服务操作映射网络驱动器示例

主体思路:

第一步:获取UNC 路径。

第二步:创建映射网络驱动器。

第三步:在相应的网络驱动器上进行相应的操作(示例中是创建文件夹)。


代码示例如下:

MapDriveKit  - 映射驱动器辅助类


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace WindowsServiceDemo
{
    /// <summary>
    /// 映射驱动器辅助类
    /// </summary>
    public class MapDriveKit
    {
        [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;
        }
        [DllImport("mpr.dll", CharSet = CharSet.Unicode, SetLastError = true)]
        public static extern int WNetGetConnection(
            [MarshalAs(UnmanagedType.LPTStr)] string localName,
            [MarshalAs(UnmanagedType.LPTStr)] StringBuilder remoteName,
            ref int length);
        /// <summary>
        /// 给定一个路径,返回的网络路径或原始路径。
        /// 例如:给定路径 P:\2008年2月29日(P:为映射的网络驱动器名),可能会返回:“//networkserver/照片/2008年2月9日”
        /// </summary> 
        /// <param name="originalPath">指定的路径</param>
        /// <returns>如果是本地路径,返回值与传入参数值一样;如果是本地映射的网络驱动器</returns> 
        public static string GetUNCPath(string originalPath)
        {
            StringBuilder sb = new StringBuilder(512);
            int size = sb.Capacity;
            if (originalPath.Length > 2 && originalPath[1] == ':')
            {
                char c = originalPath[0];
                if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
                {
                    int error = WNetGetConnection(originalPath.Substring(0, 2),
                        sb, ref size);
                    if (error == 0)
                    {
                        DirectoryInfo dir = new DirectoryInfo(originalPath);
                        string path = System.IO.Path.GetFullPath(originalPath)
                            .Substring(System.IO.Path.GetPathRoot(originalPath).Length);
                        return System.IO.Path.Combine(sb.ToString().TrimEnd(), path);
                    }
                }
            }
            return originalPath;

        }
        [DllImport("mpr.dll", CharSet = CharSet.Ansi)]
        private static extern int WNetAddConnection2(NetResource netResource, string password, string username, int flag);
        [DllImport("mpr.dll", CharSet = CharSet.Ansi)]
        private static extern int WNetCancelConnection2(string lpname, int flag, bool force);
        /// <summary>
        /// 映射网络驱动器
        /// </summary>
        /// <param name="localName">本地盘符 如U:</param>
        /// <param name="remotePath">远程路经 如\\\\172.18.118.106\\f</param>
        /// <param name="userName">远程服务器用户名</param>
        /// <param name="password">远程服务器密码</param>
        /// <returns>true映射成功,false映射失败</returns>
        public static bool WNetReflectDrive(string localName, string remotePath, string userName, string password)
        {
            NetResource netResource = new NetResource();
            netResource.dwScope = 2;
            netResource.dwType = 0x1;
            netResource.dwDisplayType = 3;
            netResource.dwUsage = 1;
            netResource.LocalName = localName;
            netResource.RemoteName = remotePath;
            netResource.provider = null;
            int ret = WNetAddConnection2(netResource, password, userName, 0);
            if (ret == 0)
                return true;
            return false;
        }

        /// <summary>
        /// 断开网路驱动器
        /// </summary>
        /// <param name="lpName">映射的盘符</param>
        /// <param name="flag">true时如果打开映射盘文件夹,也会断开,返回成功 false时打开映射盘文件夹,返回失败</param>
        /// <returns></returns>
        public static bool WNetDisconnectDrive(string lpName, bool flag)
        {
            int ret = WNetCancelConnection2(lpName, 0, flag);
            if (ret == 0)
                return true;
            return false;
        }
    }
}

调用示例:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;

namespace WindowsServiceDemo
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        static void Main()
        {
            string localMapPath = @"Y:\";

            // Get UNC Path
            string uncPath = MapDriveKit.GetUNCPath(localMapPath);

            // 映射网络驱动器(注意:第一个参数 本地盘符 正确格式 Y:  错误格式:Y:\) 
            bool mapResult = MapDriveKit.WNetReflectDrive(@"Y:", @"\\192.168.7.11\C$\01_Release", "Millet.yang@epass.net.cn", "abc@654321");


            // 映射完成后 创建 相应的目录
            string createFolder = Path.Combine(localMapPath, DateTime.Now.Ticks.ToString());
            if (!Directory.Exists(createFolder))
                Directory.CreateDirectory(createFolder);



            //ServiceBase[] ServicesToRun;
            //ServicesToRun = new ServiceBase[]
            //{
            //    new Service1()
            //};
            //ServiceBase.Run(ServicesToRun);
        }
    }
}


代码示例,点击下载



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

安得权

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值