C#复制本地文件到共享文件夹
是工作中遇到的问题。
最近chenyu哥给我提了个需求,能否在TD发布手册文件的时候,自动将其copy到某个公盘目录,以便大家取用。现状是作者必须点击TD的“下载”按钮才能下载该文件。
于是在其他同事都去参加无聊的冬至包饺子活动时,写了个插件:在postprocessing阶段成功捕获了DITA-OT输出的文件。但是File.Copy只能从本地路径复制到本地位置。而我们企业所谓的“公盘”是windows文件共享服务,其url是UNC(通用命名规则),形如\\dataserver\path\to\file
。而且还需要通过用户名和密码才能访问公盘
于是找到了这个解决方案 :
using System;
using System.IO;
using System.Runtime.InteropServices;
public class NetworkCopy
{
// Define the API to add a network drive connection
[DllImport("mpr.dll")]
private static extern int WNetAddConnection2(ref NETRESOURCE lpNetResource, string lpPassword, string lpUserName, int dwFlags);
[DllImport("mpr.dll")]
private static extern int WNetCancelConnection2(string lpName, int dwFlags, bool fForce);
// Define the NETRESOURCE structure
[StructLayout(LayoutKind.Sequential)]
public struct 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;
}
// Constants
const int RESOURCETYPE_DISK = 0x1;
const int CONNECT_UPDATE_PROFILE = 0x1;
public static void CopyFileToNetworkShare(string localFilePath, string remoteFilePath, string username, string password, string uncPath)
{
try
{
// Map the network drive (optional)
NETRESOURCE netResource = new NETRESOURCE();
netResource.dwType = RESOURCETYPE_DISK;
netResource.lpRemoteName = uncPath;
int result = WNetAddConnection2(ref netResource, password, username, CONNECT_UPDATE_PROFILE);
if (result != 0)
{
Console.WriteLine($"Error connecting to network share: {result}");
return;
}
// Now, copy the file to the network share
string destinationFilePath = Path.Combine(uncPath, remoteFilePath);
// Copy the file
File.Copy(localFilePath, destinationFilePath, overwrite: true);
Console.WriteLine("File copied successfully.");
// Disconnect the network drive (optional)
WNetCancelConnection2(uncPath, 0, true);
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
}
static void Main()
{
string localFilePath = @"C:\Users\Administrator\Desktop\test.txt";
string remoteFilePath = "foo.txt"; // The file will be copied to \\path\to\remote\foo.txt
string uncPath = @"\\raysky.net@SSL\DavWWWRoot\kod\index.php\plugin\webdav\kodbox\my"; // UNC path to the shared folder
string username = "username"; // Username for authentication
string password = "password"; // Password for authentication
CopyFileToNetworkShare(localFilePath, remoteFilePath, username, password, uncPath);
Console.ReadKey(true);
}
}
C#