C#使用用户名密码连接共享文件夹

C#使用用户名密码连接共享文件夹

创建连接

csharp 复制代码
using System.ComponentModel;
using System.Runtime.InteropServices;

namespace Tests.ConsoleApp
{
    public class ShareDirectoryConnect : IDisposable
    {
        private static readonly HashSet<Guid> _TOKENS = new HashSet<Guid>();

        private readonly string _username;
        private readonly string _password;
        private readonly string _path;
        private readonly Guid _token = Guid.NewGuid();

        private readonly object _lock = new object();

        public Guid Guid => _token;

        public ShareDirectoryConnect(string path, string username, string password)
        {
            _path = path;
            _username = username;
            _password = password;
            _token = Guid.NewGuid();
            lock (_lock)
            {
                if (_TOKENS.Count == 0)
                    Initalize();
                _TOKENS.Add(_token);
            }
        }

        public static ShareDirectoryConnect Connect(string path, string username, string password)
        {
            return new ShareDirectoryConnect(path, username, password);
        }

        private void Initalize()
        {
            USE_INFO_2 useInfo = new USE_INFO_2
            {
                ui2_remote = _path,
                ui2_username = _username,
                ui2_password = _password,
                ui2_domainname = string.Empty,
                ui2_asg_type = 0,
                ui2_usecount = 1
            };
            int result = NetUseAdd(null, 2, ref useInfo, out int paramError);
            if (result != 0)
                throw new Win32Exception(result);
        }


        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
        public struct USE_INFO_2
        {
            public string ui2_local;
            public string ui2_remote;
            public string ui2_password;
            public int ui2_status;
            public int ui2_asg_type;
            public int ui2_refcount;
            public int ui2_usecount;
            public string ui2_username;
            public string ui2_domainname;
        }

        [DllImport("netapi32.dll", CharSet = CharSet.Unicode)]
        private static extern int NetUseAdd(
            string uncServerName,
            int level,
            ref USE_INFO_2 buf,
            out int paramError);

        [DllImport("netapi32.dll", CharSet = CharSet.Unicode)]
        private static extern int NetUseDel(
            string uncServerName,
            string useName,
            int forceCond);

        public void Dispose()
        {
            lock (_lock)
            {
                if (_TOKENS.Contains(_token))
                    _TOKENS.Remove(_token);
                if (_TOKENS.Count == 0)
                    NetUseDel(null, _path, 2);
            }
        }
    }
}

测试

csharp 复制代码
internal class Program
{
    private static readonly string _username = "连接用户名";
    private static readonly string _password = "连接密码";
    private static readonly string _path = @"\\192.168.190.123\共享文件夹";
    static void Main(string[] args)
    {
        string testDir = _path + @"\test0328";
        using (ShareDirectoryConnect.Connect(_path, _username, _password))
        {
            Directory.CreateDirectory(testDir);
            Console.WriteLine("Created directory!");
        }
        List<Task> tasks = new List<Task>();
        for (int i = 0; i < 20; i++)
        {
            Task task = Task.Run(() =>
            {
                for (int j = 0; j < 5; j++)
                {
                    using (ShareDirectoryConnect.Connect(_path, _username, _password))
                    {
                        File.WriteAllText(testDir + "\\" + Guid.NewGuid().ToString() + ".txt", "Hello World");
                        Console.WriteLine("Created file!");
                    }
                }
            });
            tasks.Add(task);
        }
        Task.WaitAll(tasks.ToArray());
    }
}
相关推荐
闪电麦坤9510 分钟前
C#:尝试解析方法TryParse
开发语言·c#
我不是程序猿儿12 分钟前
【C#】构造协议帧通过串口下发
开发语言·c#
郁大锤1 小时前
如何在 Windows 上安装与配置 Tomcat
java·windows·tomcat
白烟染黑墨2 小时前
抽离BlazorWebview中的.Net与Javascript的互操作库
c#·客户端开发
小样vvv4 小时前
【分布式】深入剖析 Sentinel 限流:原理、实现
分布式·c#·sentinel
松树戈4 小时前
windows通用网线连接ubuntu实现ssh登录、桌面控制、文件共享【实操&常见问题解决思路】
linux·windows·ubuntu·ssh
闪电麦坤954 小时前
C#:常见 Console 类输入输出方法
开发语言·c#
〆、风神5 小时前
策略模式与元数据映射模式融合 JSR 380 验证规范实现枚举范围校验
windows·spring·策略模式
开开心心就好5 小时前
开启智能生活新篇:免费 APP 实现家电万能操控
java·windows·python·微信·pdf·生活·软件需求
az44yao5 小时前
windows 下 通过虚拟化拦截对一个text.txt文件的访问 如果要打开的文件名为 text.txt 提示无权限
windows