SmbFileContainer.cs 5.4 KB
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace OnlineStore
{
    /// <summary>
    /// SMB共享文件夹
    /// </summary>
    public class SmbFileContainer
    {
        private readonly NetworkCredential networkCredential;
        // Path to shared folder:
        private readonly string networkPath;
        /// <summary>
        /// SMB共享文件夹
        /// </summary>
        /// <param name="connectionInfo">连接信息</param>
        public SmbFileContainer(SmbFileConnectionInfo connectionInfo)
        {
            networkPath = connectionInfo.NetworkPath;
            networkCredential = new NetworkCredential(connectionInfo.UserName, connectionInfo.Password, connectionInfo.Domain);
        }
        /// <summary>
        /// 检查是否是有效连接
        /// </summary>
        /// <returns></returns>
        public bool IsValidConnection()
        {
            bool cRet = false;
            using (var network = new NetworkConnection($"{networkPath}", networkCredential))
            {
                var result = network.Connect();
                cRet = result == 0;
            }
            if (!cRet)
            {
                if (Directory.Exists(networkPath))
                {
                    return true;
                }
            }
            return cRet;
        }
        /// <summary>
        /// 创建文件
        /// </summary>
        /// <param name="targetFile"></param>
        /// <param name="content"></param>
        public void CreateFile(string targetFile, string content)
        {
            using (var network = new NetworkConnection(networkPath, networkCredential))
            {
                network.Connect();
                var file = System.IO.Path.Combine(networkPath, targetFile);
                System.IO.FileStream fs = System.IO.File.Create(file);
                using (System.IO.StreamWriter sw = new System.IO.StreamWriter(fs))
                {
                    sw.Write(content);
                }
            }
        }
    }
    /// <summary>
    /// SMB共享文件夹连接信息
    /// </summary>
    public class SmbFileConnectionInfo
    {
        /// <summary>
        /// 网络路径
        /// 例:@"\\192.168.101.125\Monitor\ScanResult"
        /// </summary>
        public string NetworkPath { get; set; }
        /// <summary>
        /// 用户名
        /// 例:administrator
        /// </summary>
        public string UserName { get; set; }
        /// <summary>
        /// 密码
        /// 例:123
        /// </summary>
        public string Password { get; set; }
        /// <summary>
        /// 域名
        /// </summary>
        public string Domain { get; set; } = "";
    }
    [StructLayout(LayoutKind.Sequential)]
    class NetResource
    {
        public ResourceScope Scope;
        public ResourceType ResourceType;
        public ResourceDisplaytype DisplayType;
        public int Usage;
        public string LocalName;
        public string RemoteName;
        public string Comment;
        public string Provider;
    }

    class NetworkConnection : IDisposable
    {
        private string _networkName;
        private NetworkCredential _credentials;

        public NetworkConnection(string networkName, NetworkCredential credentials)
        {
            _networkName = networkName;
            _credentials = credentials;
        }

        public int Connect()
        {
            var netResource = new NetResource()
            {
                Scope = ResourceScope.GlobalNetwork,
                ResourceType = ResourceType.Disk,
                DisplayType = ResourceDisplaytype.Share,
                RemoteName = _networkName
            };

            var userName = string.IsNullOrEmpty(_credentials.Domain)
                ? _credentials.UserName
                : string.Format(@"{0}\{1}", _credentials.Domain, _credentials.UserName);

            var result = WNetAddConnection2(
                netResource,
                _credentials.Password,
                userName,
                0);
            return result;
        }

        ~NetworkConnection()
        {
            Dispose(false);
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            WNetCancelConnection2(_networkName, 0, true);
        }

        [DllImport("mpr.dll")]
        private static extern int WNetAddConnection2(NetResource netResource,
            string password, string username, int flags);

        [DllImport("mpr.dll")]
        private static extern int WNetCancelConnection2(string name, int flags,
            bool force);
    }

    enum ResourceScope : int
    {
        Connected = 1,
        GlobalNetwork,
        Remembered,
        Recent,
        Context
    };

    enum ResourceType : int
    {
        Any = 0,
        Disk = 1,
        Print = 2,
        Reserved = 8,
    };

    enum ResourceDisplaytype : int
    {
        Generic = 0x0,
        Domain = 0x01,
        Server = 0x02,
        Share = 0x03,
        File = 0x04,
        Group = 0x05,
        Network = 0x06,
        Root = 0x07,
        Shareadmin = 0x08,
        Directory = 0x09,
        Tree = 0x0a,
        Ndscontainer = 0x0b
    };
}