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());
    }
}
相关推荐
命里有定数1 小时前
保姆级教程:在 Windows (WSL2) 下本地部署 Qwen3-ASR
windows
阔皮大师1 小时前
INote轻量文本编辑器
java·javascript·python·c#
kylezhao20192 小时前
C# 中的 SOLID 五大设计原则
开发语言·c#
啦啦啦_99993 小时前
Redis-5-doFormatAsync()方法
数据库·redis·c#
Porco.w3 小时前
C#与三菱PLC FX5U通信
网络·c#
lucky67075 小时前
Windows 上彻底卸载 Node.js
windows·node.js
编程小白20265 小时前
从 C++ 基础到效率翻倍:Qt 开发环境搭建与Windows 神级快捷键指南
开发语言·c++·windows·qt·学习
E_ICEBLUE5 小时前
PPT 批量转图片:在 Web 预览中实现翻页效果(C#/VB.NET)
c#·powerpoint·svg
凯子坚持 c7 小时前
CANN 性能剖析实战:从原始事件到交互式火焰图
windows·microsoft
JQLvopkk7 小时前
C# 轻量级工业温湿度监控系统(含数据库与源码)
开发语言·数据库·c#