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 ...
随机推荐
- zsh: /usr/local/bin/pod: bad interpreter: /System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/bin/ruby: no such file or directory
系统升级为 macOS Catalina 发现 CocoaPods 不管用了. 解决方法: 打开 iTerm2 sudo gem update --system 输入电脑密码,然后 sudo gem ...
- ViewGroup dispatchTouchEvent方法中 mFirstTouchTarget标志是否为空的含义
在ViewGroup dispatchTouchEvent方法中首次出现mFirstTouchTarget的语句为: if (actionMasked == MotionEvent.ACTION_DO ...
- ThinkPHP3.2.2实现持久登录(记住我)功能的方法
实现持久登录,即用户在登录时,勾选了"记住我"之后,无论是否关闭浏览器,只要不退出登录,在指定的时间内始终保持登录状态(缺点是在另一台电脑上登录过后,之前那台电脑就不能继续保持登录 ...
- 动态规划--最长上升子序列(LIS)的长度
l例如:对于[3,1,4,2,5],最长上升子序列的长度是3 arr = [3,1,4,5,9,2,6,5,0] def lis(arr): #dp[i]表示第i个位置的值为尾的数组的最长递增子序列的 ...
- stream,做减法,优化搜索代码。
做一个搜索,三个输入条件,求这个条件的交集.起初我的思路是按照操作的流程,一步步的来做这三个筛选. let searchResults = []; //step1 根据id搜索,得到一个子集. if ...
- 失去循环标记的Python,我这样实现跳出外层循环
不完美的Python 自从各类Python大火,感觉天上地下哪儿都有Python的一席之地,Python功夫好啊-但python有些细节上缺少其他语言的便利.今天我们就来举几个例子. 跳出外层循环 大 ...
- PyTorch最佳实践,怎样才能写出一手风格优美的代码
[摘要] PyTorch是最优秀的深度学习框架之一,它简单优雅,非常适合入门.本文将介绍PyTorch的最佳实践和代码风格都是怎样的. 虽然这是一个非官方的 PyTorch 指南,但本文总结了一年多使 ...
- CSS 3D图片翻转 ——3D Flipping Effect
效果: 代码如下: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> < ...
- mongodb验证
mongodb默认是不需要用户名和密码就可以增删查改的.要设置成需要用户名和密码访问,步骤如下: 通过下面的命令启动mongodb服务器 mongod 启动之后再登录,执行下面命令: use test ...
- 【重温基础】17.WebAPI介绍
本文是 重温基础 系列文章的第十七篇. 今日感受:挑战. 系列目录: [复习资料]ES6/ES7/ES8/ES9资料整理(个人整理) [重温基础]1-14篇 [重温基础]15.JS对象介绍 [重温基础 ...