本文介绍了如何使用C#将文件夹从一个系统复制到其他系统的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要使用C#将文件夹从我的系统复制到另一个系统。
另一个系统使用LAN连接。
怎么做
I need to copy folders from my system to another system using C#.
Another system is connected using LAN.
How to do this
推荐答案
string[] files = System.IO.Directory.GetFiles(sourcePath);
// Copy the files and overwrite destination files if they already exist.
foreach (string s in files)
{
// Use static Path methods to extract only the file name from the path.
fileName = System.IO.Path.GetFileName(s);
destFile = System.IO.Path.Combine(targetPath, fileName);
System.IO.File.Copy(s, destFile, true);
}
private void CopyFolder(string sourcePath, string DestPath, bool overWrite)
{
DirectoryInfo dir = new DirectoryInfo(sourcePath);
//iterate through all files
foreach (FileInfo file in dir.GetFiles())
{
file.CopyTo(DestPath + file.Name, overWrite);
}
}
注意:处理一些可能的错误,如文件夹存在,路径格式等。
Note: Handle some possible errors by own like folder exists, path formats etc.
IntPtr admin_token = default(IntPtr);
IntPtr dupToken = default(IntPtr);
WindowsIdentity wid_current = WindowsIdentity.GetCurrent();
WindowsIdentity wid_admin = null;
WindowsImpersonationContext wic = null;
string[] split = new string[1];
split[0] = "\\";
string[] temp = ServerName.Split(split, StringSplitOptions.RemoveEmptyEntries);
string domain = String.Empty;
string userName = ServerUserName;
string password = Password;
if (LogonUser(userName, domain, password, LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_DEFAULT, ref admin_token) != 0)
{
if (DuplicateToken(admin_token, 2, out dupToken))
{
wid_admin = new WindowsIdentity(dupToken);
wic = wid_admin.Impersonate();
try
{
// File.COPY thing
}
finally
{
if (wic != null)
{
wic.Undo();
}
if (admin_token != default(IntPtr))
CloseHandle(admin_token);
if (dupToken != default(IntPtr))
CloseHandle(dupToken);
}
}
这篇关于如何使用C#将文件夹从一个系统复制到其他系统的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!