新文章 网摘 文章 随笔 日记

访问网络共享文件夹

1、建立一次连接,可以长期使用而无需每次访问都连接。
2、建立连接前先断开旧的连接。
3、在Global.asax中程序启动时连接,然后上传文件或下载文件什么的就不用再次连接了。

代码:

using System.Runtime.InteropServices;
namespace Phoenix.Modules.Common.Service.Uploads
{

    public enum ERROR_ID
    {
        ERROR_SUCCESS = 0, // Success 
        ERROR_BUSY = 170,
        ERROR_MORE_DATA = 234,
        ERROR_NO_BROWSER_SERVERS_FOUND = 6118,
        ERROR_INVALID_LEVEL = 124,
        ERROR_ACCESS_DENIED = 5,
        ERROR_INVALID_PASSWORD = 86,
        ERROR_INVALID_PARAMETER = 87,
        ERROR_BAD_DEV_TYPE = 66,
        ERROR_NOT_ENOUGH_MEMORY = 8,
        ERROR_NETWORK_BUSY = 54,
        ERROR_BAD_NETPATH = 53,
        ERROR_NO_NETWORK = 1222,
        ERROR_INVALID_HANDLE_STATE = 1609,
        ERROR_EXTENDED_ERROR = 1208,
        ERROR_DEVICE_ALREADY_REMEMBERED = 1202,
        ERROR_NO_NET_OR_BAD_PATH = 1203
    }

    public enum RESOURCE_SCOPE
    {
        RESOURCE_CONNECTED = 1,
        RESOURCE_GLOBALNET = 2,
        RESOURCE_REMEMBERED = 3,
        RESOURCE_RECENT = 4,
        RESOURCE_CONTEXT = 5
    }

    public enum RESOURCE_TYPE
    {
        RESOURCETYPE_ANY = 0,
        RESOURCETYPE_DISK = 1,
        RESOURCETYPE_PRINT = 2,
        RESOURCETYPE_RESERVED = 8,
    }

    public enum RESOURCE_USAGE
    {
        RESOURCEUSAGE_CONNECTABLE = 1,
        RESOURCEUSAGE_CONTAINER = 2,
        RESOURCEUSAGE_NOLOCALDEVICE = 4,
        RESOURCEUSAGE_SIBLING = 8,
        RESOURCEUSAGE_ATTACHED = 16,
        RESOURCEUSAGE_ALL = (RESOURCEUSAGE_CONNECTABLE | RESOURCEUSAGE_CONTAINER | RESOURCEUSAGE_ATTACHED),
    }

    public enum RESOURCE_DISPLAYTYPE
    {
        RESOURCEDISPLAYTYPE_GENERIC = 0,
        RESOURCEDISPLAYTYPE_DOMAIN = 1,
        RESOURCEDISPLAYTYPE_SERVER = 2,
        RESOURCEDISPLAYTYPE_SHARE = 3,
        RESOURCEDISPLAYTYPE_FILE = 4,
        RESOURCEDISPLAYTYPE_GROUP = 5,
        RESOURCEDISPLAYTYPE_NETWORK = 6,
        RESOURCEDISPLAYTYPE_ROOT = 7,
        RESOURCEDISPLAYTYPE_SHAREADMIN = 8,
        RESOURCEDISPLAYTYPE_DIRECTORY = 9,
        RESOURCEDISPLAYTYPE_TREE = 10,
        RESOURCEDISPLAYTYPE_NDSCONTAINER = 11
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct NETRESOURCE
    {
        public RESOURCE_SCOPE dwScope;
        public RESOURCE_TYPE dwType;
        public RESOURCE_DISPLAYTYPE dwDisplayType;
        public RESOURCE_USAGE dwUsage;

        [MarshalAs(UnmanagedType.LPStr)]
        public string lpLocalName;

        [MarshalAs(UnmanagedType.LPStr)]
        public string lpRemoteName;

        [MarshalAs(UnmanagedType.LPStr)]
        public string lpComment;

        [MarshalAs(UnmanagedType.LPStr)]
        public string lpProvider;
    }

    public class NetworkConnection
    {

        [DllImport("mpr.dll")]
        public static extern int WNetAddConnection2A(NETRESOURCE[] lpNetResource, string lpPassword, string lpUserName, int dwFlags);

        [DllImport("mpr.dll")]
        public static extern int WNetCancelConnection2A(string shareName, int dwFlags, int fForce);


        public static int Connect(string remotePath, string localPath, string username, string password)
        {
            NETRESOURCE[] shareDriver = new NETRESOURCE[1];
            shareDriver[0].dwScope = RESOURCE_SCOPE.RESOURCE_GLOBALNET;
            shareDriver[0].dwType = RESOURCE_TYPE.RESOURCETYPE_DISK;
            shareDriver[0].dwDisplayType = RESOURCE_DISPLAYTYPE.RESOURCEDISPLAYTYPE_SHARE;
            shareDriver[0].dwUsage = RESOURCE_USAGE.RESOURCEUSAGE_CONNECTABLE;
            shareDriver[0].lpLocalName = localPath;
            shareDriver[0].lpRemoteName = remotePath;

            Disconnect(localPath);
            int ret = WNetAddConnection2A(shareDriver, password, username, 1);

            return ret;
        }

        public static int Disconnect(string localPath)
        {
            return WNetCancelConnection2A(localPath, 1, 1);
        }

    }

}


using System;
using System.Configuration;
using System.Net;
using System.Net.Configuration;
using Phoenix.Modules.Common.Infrastructure.Models;
using Phoenix.Modules.Common.Service.Uploads;

namespace Application.SpareParts
{
    public class GlobalConfig
    {
        public const string ApplicationKey = "6B856340-E9D3-407B-BC0D-2DB002AED391";
        /// <summary>
        /// 缓存过期时间
        /// </summary>
        private static TimeSpan _cacheExpiresMinute;
        public static TimeSpan CacheExpiresMinute
        {
            get
            {
                if (!(Math.Abs(_cacheExpiresMinute.TotalMilliseconds) < 1)) return _cacheExpiresMinute;
                int minute;
                int.TryParse(ConfigurationManager.AppSettings["CacheExpiresMinute"], out minute);
                _cacheExpiresMinute = new TimeSpan(0, minute, 0);
                return _cacheExpiresMinute;
            }
        }
        /// <summary>
        /// 用户权限缓存Key前缀
        /// </summary>
        public static string UserPrivilegesCacheKey(string userKey)
            => $"UserPrivileges_{userKey}";
        /// <summary>
        /// 菜单树缓存Key
        /// </summary>
        public static string MenuTreeCacheKey(string userKey)
            => $"MenuTree_{userKey}";
        public static string MenuBootstrapTreeCacheKey => $"{ApplicationKey}_MenuBootstrapTree";
        /// <summary>
        /// 所有权限缓存的Key
        /// </summary>
        public static string AllPrivilegesCacheKey => $"{ApplicationKey}_AllPrivileges";
        /// <summary>
        /// 文件上传相对路径
        /// </summary>
        public static string ApplicationStaticRelativePath => "Uploads";
        /// <summary>
        /// 文件上传的根目录
        /// </summary>
        private static string _uploadRootDirectory;
        public static string UploadRootDirectory
        {
            get
            {
                if (!string.IsNullOrWhiteSpace(_uploadRootDirectory))
                {
                    return _uploadRootDirectory;
                }
                _uploadRootDirectory = ConfigurationManager.AppSettings["UploadRootDirectory"];
                return _uploadRootDirectory;
            }


        }


        /// <summary>
        /// 文件上传的根目录用户名
        /// </summary>
        private static string _uploadRootDirectoryUser;
        public static string UploadRootDirectoryUser
        {
            get
            {
                if (!string.IsNullOrWhiteSpace(_uploadRootDirectoryUser))
                {
                    return _uploadRootDirectoryUser;
                }
                _uploadRootDirectoryUser = ConfigurationManager.AppSettings["UploadRootDirectoryUser"];
                return _uploadRootDirectoryUser;
            }


        }


        /// <summary>
        /// 文件上传的根目录密码
        /// </summary>
        private static string _uploadRootDirectoryPwd;
        public static string UploadRootDirectoryPwd
        {
            get
            {
                if (!string.IsNullOrWhiteSpace(_uploadRootDirectoryPwd))
                {
                    return _uploadRootDirectoryPwd;
                }
                _uploadRootDirectoryPwd = ConfigurationManager.AppSettings["UploadRootDirectoryPwd"];
                return _uploadRootDirectoryPwd;
            }


        }

        /// <summary>
        /// 文件上传最大容量,計量單位為字節,默認为3MB
        /// </summary>
        private static int _maxUploadLengthLimit;
        public static int MaxUploadLengthLimit
        {
            get
            {
                if (_maxUploadLengthLimit != 0)
                {
                    return _maxUploadLengthLimit;
                }

                int imgSize;
                int.TryParse(ConfigurationManager.AppSettings["MaxUploadLengthLimit"], out imgSize);

                imgSize = imgSize * 1024;//换算成字节

                if (imgSize == 0)
                {
                    imgSize = 1 * 1024 * 1024;//默认1MB
                }

                _maxUploadLengthLimit = imgSize;
                return _maxUploadLengthLimit;
            }


        }

        public static bool AllowClearOldData
        {
            get
            {
                bool allow;
                bool.TryParse(ConfigurationManager.AppSettings["AllowClearOldData"], out allow);
                return allow;
            }
        }

        public static bool UploadNeedToConnect
        {
            get
            {
                bool need;
                bool.TryParse(ConfigurationManager.AppSettings["UploadNeedToConnect"], out need);
                return need;
            }
        }

        private static MailSetting _mailSetting;
        public static MailSetting MailSetting
        {
            get
            {
                if (_mailSetting == null)
                {
                    SmtpSection netSmtpMailSection = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
                    _mailSetting = new MailSetting
                    {
                        Host = netSmtpMailSection.Network.Host,
                        Port = netSmtpMailSection.Network.Port,
                        UserName = netSmtpMailSection.Network.UserName,
                        Password = netSmtpMailSection.Network.Password
                    };
                }

                return _mailSetting;
            }
        }
        /// <summary>
        /// 域名
        /// </summary>
        private static string _domain;
        /// <summary>
        /// 域名
        /// </summary>
        public static string Domain => _domain ?? (_domain = ConfigurationManager.AppSettings["Domain"]);
        public static ShareFoldConnectInfo ShareFoldConnectInfo => new ShareFoldConnectInfo()
        {
            NeedToConnect = UploadNeedToConnect,
            User = UploadRootDirectoryUser,
            Password = UploadRootDirectoryPwd,
            UserNameWithDomain= string.IsNullOrEmpty(UploadRootDirectory)
                ? UploadRootDirectoryUser
                : $@"{UploadRootDirectory}\{UploadRootDirectoryUser}",
            Folder = UploadRootDirectory
        };

        public static ConnectToSharedFolder ShareFoldNetworkCredential()
        {
            if (!UploadNeedToConnect)
            {
                return null;
            }
            NetworkCredential credentials = new NetworkCredential(UploadRootDirectoryUser, UploadRootDirectoryPwd);
            return new ConnectToSharedFolder(UploadRootDirectory, credentials);
        }

        public static void ConnectSharedFolder()
        {
            var info = ShareFoldConnectInfo;
            string localPath = "X:";
            if (info.NeedToConnect)
            {
                NetworkConnection.Connect(info.Folder, localPath, info.User, info.Password);
            }
        }
    }
}

Global.asax中:

            //連接共享文件夾
            GlobalConfig.ConnectSharedFolder();

 

posted @ 2020-02-13 10:20  岭南春  阅读(327)  评论(0)    收藏  举报