using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks; namespace TFCP
{
/// <summary>
/// Provides access to a network share.
/// </summary>
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 = ; private const int ERROR_ACCESS_DENIED = ;
private const int ERROR_ALREADY_ASSIGNED = ;
private const int ERROR_BAD_DEVICE = ;
private const int ERROR_BAD_NET_NAME = ;
private const int ERROR_BAD_PROVIDER = ;
private const int ERROR_CANCELLED = ;
private const int ERROR_EXTENDED_ERROR = ;
private const int ERROR_INVALID_ADDRESS = ;
private const int ERROR_INVALID_PARAMETER = ;
private const int ERROR_INVALID_PASSWORD = ;
private const int ERROR_MORE_DATA = ;
private const int ERROR_NO_MORE_ITEMS = ;
private const int ERROR_NO_NET_OR_BAD_PATH = ;
private const int ERROR_NO_NETWORK = ; private const int ERROR_BAD_PROFILE = ;
private const int ERROR_CANNOT_OPEN_PROFILE = ;
private const int ERROR_DEVICE_IN_USE = ;
private const int ERROR_NOT_CONNECTED = ;
private const int ERROR_OPEN_FILES = ; #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 = ;
public int dwType = ;
public int dwDisplayType = ;
public int dwUsage = ;
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, , 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></filterpriority>
public void Dispose()
{
this.DisconnectFromShare(this._remoteUncName);
}
}
} static void PathCopyToRemoteDemo()
{
string destFile = @"\\RemotePCName\SharedFile";
string sourceFile = @"C:\myfolder\mytxt.txt";
string fileName = Path.GetFileName(sourceFile);
string remotePCName = "remotePCName";
string remotePCDOMAINName = "remotePCDOMAINName";
string remotePCUserName = "RemotePCPassword";
string remotePCUserPwd = "remotePCUserPwd";
string destFullName = Path.Combine(destFile, fileName);
using (NetworkShareAccesser.Access(remotePCName, remotePCDOMAINName, remotePCUserName, remotePCUserPwd))
{
File.Copy(sourceFile, destFullName);
}
}

based on https://stackoverflow.com/questions/659013/accessing-a-shared-file-unc-from-a-remote-non-trusted-domain-with-credentials

C# transfer local file to remote server based on File.Copy的更多相关文章

  1. Golang : Forwarding a local port to a remote server example

    原文:https://socketloop.com/tutorials/golang-forwarding-a-local-port-to-a-remote-server-example 端口转发, ...

  2. vscode local attach 和 remote debug

    VSCode是MS推出的一款免费的开源并跨平台的轻量级代码编辑器,内置Git和Debug等常用功能,强大的插件扩展功能以及简单的配置几乎可以打造成任意编程语言的IDE.本文简单聊一下其本地attach ...

  3. CHECK_NRPE: Received 0 bytes from daemon. Check the remote server logs for error messages.

    今天,在用icinga服务器端测试客户端脚本时,报如下错误: [root@mysql-server1 etc]# /usr/local/icinga/libexec/check_nrpe -H 192 ...

  4. 奇葩问题:This file could not be checked in because the original version of the file on the server was moved or deleted. A new version of this file has been saved to the server, but your check-in comments were not saved

    "This file could not be checked in because the original version of the file on the server was m ...

  5. WinRM不起作用 Connecting to remote server failed with the following error message : WinRM cannot complete the operation

    当我运行下面的 powershell  脚本时: $FarmAcct = 'domain\user'  $secPassword = ConvertTo-SecureString 'aaa' -AsP ...

  6. org.openqa.selenium.remote.UnreachableBrowserException: Could not start a new session. Possible causes are invalid address of the remote server or br

    WARN <init>, HHH000409: Using org.hibernate.id.UUIDHexGenerator which does not generate IETF R ...

  7. [转]How to Import a Text File into SQL Server 2012

    Importing a using the OpenRowSet() Function The OPENROWSET bulk row set provider is accessed by call ...

  8. Jmeter-Maven-Plugin高级应用:Remote Server Configuration

    Remote Server Configuration Pages 12 Home Adding additional libraries to the classpath Advanced Conf ...

  9. psql: could not connect to server: No such file or directory

    postgresql报错: psql: could not connect to server: No such file or directory         Is the server run ...

随机推荐

  1. .Net Core+Vue.js模块化前后端分离快速开发框架NetModular更新日志(2019-12-08)

    源码 GitHub:https://github.com/iamoldli/NetModular 码云:https://gitee.com/laoli/NetModular 欢迎star~ 文档 ht ...

  2. 01Shell入门02-echo和printf

    输出方式 小知识 echo echo -e 可以控制字体颜色和背景颜色输出 示例 echo -e "\033[41;36m Hello world \033[0m" [root@h ...

  3. vuex模块化。

    项目结构: 1:在src下新建目录store,然后再建storemodule.js文件,把 上篇 store.js文件抽出来: import Vue from 'vue' import Vuex fr ...

  4. UVA-136Ugly numbers

    Ugly numbers are numbers whose only prime factors are 2, 3 or 5. The sequence 1, 2, 3, 4, 5, 6, 8, 9 ...

  5. 60%的人不懂Python进程Process,你懂吗?

    前言本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理.作者:蒋狗    新手注意:如果你Python基础学的不够扎实,遇问题没人解答 ...

  6. 【Webpack】320- Webpack4 入门手册(共 18 章)(下)

    介绍 1. 背景 最近和部门老大,一起在研究团队[EFT - 前端新手村]的建设,目的在于:帮助新人快速了解和融入公司团队,帮助零基础新人学习和入门前端开发并且达到公司业务开发水平. 本文也是属于[E ...

  7. 大数据学习笔记——Spark完全分布式完整部署教程

    Spark完全分布式完整部署教程 继Mapreduce之后,作为新一代并且是主流的计算引擎,学好Spark是非常重要的,这一篇博客会专门介绍如何部署一个分布式的Spark计算框架,在之后的博客中,更会 ...

  8. 使用脚本安装 Docker

    使用脚本安装 Docker 1.使用 sudo 或 root 权限登录 Centos. 2.确保 yum 包更新到最新. $ sudo yum update 3.执行 Docker 安装脚本. $ c ...

  9. 2019年12月18日Linux开发手记

    安装idle3: 1.端输入apt install idle3 以安装 2.安装完成后在终端输入idle以启动 配置pip: 1.终端输入apt install python3-pip 使用pip配置 ...

  10. android开发针对小米、三星、华为8.0+系统个别型号打开应用闪退

    最近开发中有个别客户反馈新换的三星.小米或者华为手机打开应用就闪退,而且是个别型号.针对这种情况特别查阅了一些资料,原因是8.0+系统的手机不允许后台创建服务,那么怎么修改呢,请看代码: 1.修改启动 ...