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());
    }
}
相关推荐
玩泥巴的37 分钟前
一分钟实现.NET与飞书长连接的WebSocket架构
c#·.net·二次开发·飞书
mudtools39 分钟前
一分钟实现.NET与飞书长连接的WebSocket架构
后端·c#·.net
Sunsets_Red43 分钟前
二项式定理
java·c++·python·算法·数学建模·c#
技术小甜甜1 小时前
【系统实战排坑】电脑重启后总是直接进入 Windows,按键无效进不了 BIOS?最全解决方案在这里!
windows·电脑·蓝屏
阿富软件园1 小时前
文档搜索利器——“搜索文本”全能版 支持多格式 加 内容搜索
windows·电脑·开源软件
取个名字太难了a1 小时前
任务段提权实验
windows
2301_793069822 小时前
Linux Ubuntu/Windows 双系统 分区挂载指南
linux·windows·ubuntu
道路与代码之旅2 小时前
Windows 10 中以 WSL 驱 Ubuntu 记
linux·windows·ubuntu
星空椰2 小时前
Windows 使用nvm多版本管理node.js
windows·node.js
源之缘-OFD先行者3 小时前
定制化 Live555 实战:按需开发低耗 RTSP 服务器,完美适配 C# 项目
运维·服务器·c#