C# transfer local file to remote server based on File.Copy
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);
}
}
C# transfer local file to remote server based on File.Copy的更多相关文章
- Golang : Forwarding a local port to a remote server example
原文:https://socketloop.com/tutorials/golang-forwarding-a-local-port-to-a-remote-server-example 端口转发, ...
- vscode local attach 和 remote debug
VSCode是MS推出的一款免费的开源并跨平台的轻量级代码编辑器,内置Git和Debug等常用功能,强大的插件扩展功能以及简单的配置几乎可以打造成任意编程语言的IDE.本文简单聊一下其本地attach ...
- 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 ...
- 奇葩问题: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 ...
- 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 ...
- 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 ...
- [转]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 ...
- Jmeter-Maven-Plugin高级应用:Remote Server Configuration
Remote Server Configuration Pages 12 Home Adding additional libraries to the classpath Advanced Conf ...
- 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 ...
随机推荐
- java8 按两个属性分组,并返回扁平List; stream排序
--------------- java8 按两个属性分组,并返回扁平List /** * 设置大区小区分组排序 * @param dtoList */ private List<Perform ...
- 2019-2020-1 20199304《Linux内核原理与分析》第六周作业
第五章 系统调用的三层机制(下) 1.往MenuOS中添加命令 (1)首先进入LinuxKernel文件夹,将menu目录删除.然后再git clone克隆下载更新了版本之后的menu目录(包含tim ...
- css练习——两列左窄右kuan型
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8" ...
- Spring Boot 最流行的 16 条实践解读!【华为云技术分享】
置顶:华为云618大促火热进行中,全场1折起,免费抽主机,消费满额送P30 Pro,点此抢购. Spring Boot是最流行的用于开发微服务的Java框架.在本文中,将与大家分享自2016年以来笔者 ...
- 在Linux下生成crypt加密密码
[摘要]当我们用红帽Kickstart脚本或useradd或其他方式写东西的时候,经常会需要用到crypt命令加密生成的密码格式.那么,有没有其他方式可以生成这种格式的密码?事实上,方法有很多 1.我 ...
- Python基础班学习笔记
本博客采用思维导图式笔记,所有思维导图均为本人亲手所画.因为本人也是初次学习Python语言所以有些知识点可能不太全. 基础班第一天学习笔记:链接 基础班第二天学习笔记:链接 基础班第三天学习笔记:链 ...
- elasticSerach 知识学习
一 介绍: ElasticSearch是一个基于Lucene的搜索服务器.它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口.Elasticsearch是用Java语言开发的, ...
- 在 Xcode9 中自定义文件头部注释和其他文本宏
在 Xcode9 中自定义文件头部注释和其他文本宏 . 参考链接 注意生成的plist文件的名称为IDETemplateMacros.plist 在plist文件里设置自己想要的模板 注意plist存 ...
- IOS UIAlertView(警告框)方法总结
转自:my.oschina.net/u/2340880/blog/408873?p=1 IOS中UIAlertView(警告框)常用方法总结 一.初始化方法 - (instancetype)initW ...
- [TimLinux] 理解selinux
1. 概念 SELinux有三种工作模式:Enforcing, Permissive, disabled.Enforcing对应又有几种修饰(targeted, minimum, mls). 2. 解 ...