NetworkShareAccesser: 远程PC1 文件 copy 到PC2 文件夹

Usage:

string strRepoBundlePath = @"\\at1-repo01\ATE\Bundles\SharePoint\Open\denyopen.zip";
string strRemoteBundle = @"\\"+serverHostName+@"\c$\denyopen.zip";

using (NetworkShareAccesser.Access(serverHostName, domain, userName, password))
{
       File.Copy(@strRepoBundlePath, @strRemoteBundle);
}

WARNING: Please make absolutely sure, that Dispose of the NetworkShareAccesser is called (even if you app crashes!), otherwise an open connection will remain on Windows. You can see all open connections by opening the cmd prompt and enter net use.

The Code:

public class NetworkShareAccesser : IDisposable
{
    private string _remoteUncName;
    private string _remoteComputerName;

    public string RemoteComputerName
    {
        get
        {
            return this._remoteComputerName;
        }
        set
        {
            this._remoteComputerName = value;
            this._remoteUncName = @"\\" + this._remoteComputerName;
        }
    }

    public string UserName
    {
        get;
        set;
    }
    public string Password
    {
        get;
        set;
    }

    #region Consts

    private const int RESOURCE_CONNECTED = 0x00000001;
    private const int RESOURCE_GLOBALNET = 0x00000002;
    private const int RESOURCE_REMEMBERED = 0x00000003;

    private const int RESOURCETYPE_ANY = 0x00000000;
    private const int RESOURCETYPE_DISK = 0x00000001;
    private const int RESOURCETYPE_PRINT = 0x00000002;

    private const int RESOURCEDISPLAYTYPE_GENERIC = 0x00000000;
    private const int RESOURCEDISPLAYTYPE_DOMAIN = 0x00000001;
    private const int RESOURCEDISPLAYTYPE_SERVER = 0x00000002;
    private const int RESOURCEDISPLAYTYPE_SHARE = 0x00000003;
    private const int RESOURCEDISPLAYTYPE_FILE = 0x00000004;
    private const int RESOURCEDISPLAYTYPE_GROUP = 0x00000005;

    private const int RESOURCEUSAGE_CONNECTABLE = 0x00000001;
    private const int RESOURCEUSAGE_CONTAINER = 0x00000002;

    private const int CONNECT_INTERACTIVE = 0x00000008;
    private const int CONNECT_PROMPT = 0x00000010;
    private const int CONNECT_REDIRECT = 0x00000080;
    private const int CONNECT_UPDATE_PROFILE = 0x00000001;
    private const int CONNECT_COMMANDLINE = 0x00000800;
    private const int CONNECT_CMD_SAVECRED = 0x00001000;

    private const int CONNECT_LOCALDRIVE = 0x00000100;

    #endregion

    #region Errors

    private const int NO_ERROR = 0;

    private const int ERROR_ACCESS_DENIED = 5;
    private const int ERROR_ALREADY_ASSIGNED = 85;
    private const int ERROR_BAD_DEVICE = 1200;
    private const int ERROR_BAD_NET_NAME = 67;
    private const int ERROR_BAD_PROVIDER = 1204;
    private const int ERROR_CANCELLED = 1223;
    private const int ERROR_EXTENDED_ERROR = 1208;
    private const int ERROR_INVALID_ADDRESS = 487;
    private const int ERROR_INVALID_PARAMETER = 87;
    private const int ERROR_INVALID_PASSWORD = 1216;
    private const int ERROR_MORE_DATA = 234;
    private const int ERROR_NO_MORE_ITEMS = 259;
    private const int ERROR_NO_NET_OR_BAD_PATH = 1203;
    private const int ERROR_NO_NETWORK = 1222;

    private const int ERROR_BAD_PROFILE = 1206;
    private const int ERROR_CANNOT_OPEN_PROFILE = 1205;
    private const int ERROR_DEVICE_IN_USE = 2404;
    private const int ERROR_NOT_CONNECTED = 2250;
    private const int ERROR_OPEN_FILES = 2401;

    #endregion

    #region PInvoke Signatures

    [DllImport("Mpr.dll")]
    private static extern int WNetUseConnection(
        IntPtr hwndOwner,
        NETRESOURCE lpNetResource,
        string lpPassword,
        string lpUserID,
        int dwFlags,
        string lpAccessName,
        string lpBufferSize,
        string lpResult
        );

    [DllImport("Mpr.dll")]
    private static extern int WNetCancelConnection2(
        string lpName,
        int dwFlags,
        bool fForce
        );

    [StructLayout(LayoutKind.Sequential)]
    private class NETRESOURCE
    {
        public int dwScope = 0;
        public int dwType = 0;
        public int dwDisplayType = 0;
        public int dwUsage = 0;
        public string lpLocalName = "";
        public string lpRemoteName = "";
        public string lpComment = "";
        public string lpProvider = "";
    }

    #endregion

    /// <summary>
    /// Creates a NetworkShareAccesser for the given computer name. The user will be promted to enter credentials
    /// </summary>
    /// <param name="remoteComputerName"></param>
    /// <returns></returns>
    public static NetworkShareAccesser Access(string remoteComputerName)
    {
        return new NetworkShareAccesser(remoteComputerName);
    }

    /// <summary>
    /// Creates a NetworkShareAccesser for the given computer name using the given domain/computer name, username and password
    /// </summary>
    /// <param name="remoteComputerName"></param>
    /// <param name="domainOrComuterName"></param>
    /// <param name="userName"></param>
    /// <param name="password"></param>
    public static NetworkShareAccesser Access(string remoteComputerName, string domainOrComuterName, string userName, string password)
    {
        return new NetworkShareAccesser(remoteComputerName,
                                        domainOrComuterName + @"\" + userName,
                                        password);
    }

    /// <summary>
    /// Creates a NetworkShareAccesser for the given computer name using the given username (format: domainOrComputername\Username) and password
    /// </summary>
    /// <param name="remoteComputerName"></param>
    /// <param name="userName"></param>
    /// <param name="password"></param>
    public static NetworkShareAccesser Access(string remoteComputerName, string userName, string password)
    {
        return new NetworkShareAccesser(remoteComputerName,
                                        userName,
                                        password);
    }

    private NetworkShareAccesser(string remoteComputerName)
    {
        RemoteComputerName = remoteComputerName;

        this.ConnectToShare(this._remoteUncName, null, null, true);
    }

    private NetworkShareAccesser(string remoteComputerName, string userName, string password)
    {
        RemoteComputerName = remoteComputerName;
        UserName = userName;
        Password = password;

        this.ConnectToShare(this._remoteUncName, this.UserName, this.Password, false);
    }

    private void ConnectToShare(string remoteUnc, string username, string password, bool promptUser)
    {
        NETRESOURCE nr = new NETRESOURCE
        {
            dwType = RESOURCETYPE_DISK,
            lpRemoteName = remoteUnc
        };

        int result;
        if (promptUser)
        {
            result = WNetUseConnection(IntPtr.Zero, nr, "", "", CONNECT_INTERACTIVE | CONNECT_PROMPT, null, null, null);
        }
        else
        {
            result = WNetUseConnection(IntPtr.Zero, nr, password, username, 0, null, null, null);
        }

        if (result != NO_ERROR)
        {
            throw new Win32Exception(result);
        }
    }

    private void DisconnectFromShare(string remoteUnc)
    {
        int result = WNetCancelConnection2(remoteUnc, CONNECT_UPDATE_PROFILE, false);
        if (result != NO_ERROR)
        {
            throw new Win32Exception(result);
        }
    }

    /// <summary>
    /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
    /// </summary>
    /// <filterpriority>2</filterpriority>
    public void Dispose()
    {
        this.DisconnectFromShare(this._remoteUncName);
    }
}
时间: 2024-10-29 20:44:01

NetworkShareAccesser: 远程PC1 文件 copy 到PC2 文件夹的相关文章

hadoop搭建杂记:Linux下不同linux主机之间文件copy的scp命令

不同的Linux之间copy文件常用有3种方法: 不同的Linux之间copy文件常用有3种方法: ①ftp 就是其中一台Linux安装ftp Server,这样可以另外一台使用ftp的程序来进行文件的copy. ②采用samba服务 就是类似Windows文件copy 的方式来操作,比较简洁方便. ③利用scp命令来进行文件复制. scp是安全机制的文件copy,基于ssh登录.操作起来比较方便,比如要把master机当前一个文件copy到slave1机上,可以如下命令. scp ./test

利用datafile copy将数据文件重命名

思路: o 利用RMAN对数据文件做copy o 将数据文件offline o switch文件名,这一步将更改控制文件中数据文件对应的文件名 o recover数据文件 o 将数据文件online,恢复生产 注:也可以利用这种思路做DATABASE COPY,然后做SWITCH DATABASE,迁移数据库... 实验过程如下: ====================================== SQL> archive log list; Database log mode    

C# FTP远程服务器返回错误:(550) 文件不可用(例如,未找到文件,无法访问文件)

今天用代码删除FTP服务器上的目录时候,报错:远程服务器返回错误:(550) 文件不可用(例如,未找到文件,无法访问文件). 习惯性的google,不外乎以下几点: 1.URL路径不对,看看有没有多加空格,或者大小写问题 2.权限是否足 3.需要反复连接的时候,如GetFileList,需要递归获得所有文件,keepAlive则设成false,一个查询请求完了后就关闭. 照做后问题依旧,很苦恼! 然后在FTP上建立了一个空目录,删除之,竟然能删除了.... 所以,找到原因:删除目录,该目录下不能

C# 文件Copy

文件Copy有以下几种方法: 1.Copy string sourceFile = @"c:\temp\New Text Document.txt"; string destinationFile = @"c:\temp\test.txt"; bool isrewrite=true; // true=覆盖已存在的同名文件,false则反之 System.IO.File.Copy(sourcePath, targetPath, isrewrite); 2.CopyTo

SFTP远程连接服务器上传下载文件-vs2010项目实例

本项目仅测试远程连接服务器,支持上传,下载文件,更多功能开发请看API自行开发. 环境:win7系统,vs2010 vs2010项目实例下载地址:CSDN下载 如果没有CSDN积分,百度网盘下载(密码:uxnt) 文件目录介绍: 1.libssh2.sln是vs2010的解决方案,用vs2010打开(如图1所示): include是需要导入的头文件,lib是需要使用的lib文件(如图2所示): 图1 图2 2.解决方案:"libssh2"(如图3所示) 这里只需要编译运行demo项目即

Linux下不借助工具实现远程linux服务器上传下载文件

# Linux下不借助工具实现远程linux服务器上传下载文件 ## 简介 - Linux下自带ssh工具,可以实现远程Linux服务器的功能- Linux下自带scp工具,可以实现文件传输功能 ## 登录服务器 - `ssh [email protected]` 登录服务器```PC:~$ ssh [email protected][email protected]'s password: ``` ## 文件传输 - 下载文件- `scp [email protected]:/data/log

Python脚本远程Linux创建目录、上传文件

最近这段时间,经常通过xftp在服务器上创建目录并上传文件,繁琐的事一直循环的做,因此一直在想通过Python脚本能自动创建目录,上传文件,询问公司大佬和百度终于找到了方法,接下来看看. 一. 说明 主要安装两个模块paramiko与scp,功能即可实现 paramiko是一个基于SSH用于连接远程服务器并执行相关操作(SSHClient和SFTPClinet,即一个是远程连接,一个是上传下载服务),使用该模块可以对远程服务器进行命令或文件操作,值得一说的是,fabric和ansible内部的远

PHP表单处理、会话管理、文件上传、文件处理、执行函数(10.8 第十六天)

表单处理 服务器接收用户发过来的数据方式: $_GET 接收用户以GET方式发过来的数据 $_POST 接收用户以POST方式发过来的数据 $_COOKIE 接收用户COOKIE $_REQUEST 接收用户发过来的数据 htmlspecialchars() 实体化编码 文件包含:通过一些文件包含的函数将本地或者远程服务器中文件包含解析到当前服务器中,达到文件读取.代码利用.函数调用等目的 include "文件名 "==include("文件名") include

文件查询之三:文件和目录的批量操作

经过之前两篇的随笔已经可以将所需要的文件和目录查找出来,并且保存在一个文档中,所以现在就是利用保存文件或目录的文档来进行批量处理,对文件或目录进行批量的 删除.复制和移动.主要是用到shutil模块中的函数和os模块中的函数进行一系列的操作.shutil模块存在大量的文件操作和目录操作的函数,包括常用的移动文件或复制文件 等操作,其中os和shutil下对于函数的功能存在交集,只不过相同功能下的函数名存在差异,函数上的细节处理方面也有可能不一样.在这里主要的是讲shutil模块下的函数. 首先是