У меня есть папка с 10 текстовыми файлами на диске C:\TEXTFILES\на моей машине. Я хочу полностью скопировать папку TEXTFILES и ее содержимое с моей машины на другую машину. Как скопировать то же самое с помощью С#.
Копирование папки в С#
Ответ 1
using System;
using System.IO;
class DirectoryCopyExample
{
static void Main()
{
DirectoryCopy(".", @".\temp", true);
}
private static void DirectoryCopy(
string sourceDirName, string destDirName, bool copySubDirs)
{
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
DirectoryInfo[] dirs = dir.GetDirectories();
// If the source directory does not exist, throw an exception.
if (!dir.Exists)
{
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ sourceDirName);
}
// If the destination directory does not exist, create it.
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
}
// Get the file contents of the directory to copy.
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
// Create the path to the new copy of the file.
string temppath = Path.Combine(destDirName, file.Name);
// Copy the file.
file.CopyTo(temppath, false);
}
// If copySubDirs is true, copy the subdirectories.
if (copySubDirs)
{
foreach (DirectoryInfo subdir in dirs)
{
// Create the subdirectory.
string temppath = Path.Combine(destDirName, subdir.Name);
// Copy the subdirectories.
DirectoryCopy(subdir.FullName, temppath, copySubDirs);
}
}
}
}
От MSDN
Ответ 2
private void copyDirectory(string strSource, string strDestination)
{
if (!Directory.Exists(strDestination))
{
Directory.CreateDirectory(strDestination);
}
DirectoryInfo dirInfo = new DirectoryInfo(strSource);
FileInfo[] files = dirInfo.GetFiles();
foreach(FileInfo tempfile in files )
{
tempfile.CopyTo(Path.Combine(strDestination,tempfile.Name));
}
DirectoryInfo[] directories = dirInfo.GetDirectories();
foreach(DirectoryInfo tempdir in directories)
{
copyDirectory(Path.Combine(strSource, tempdir.Name), Path.Combine(strDestination, tempdir.Name));
}
}
Ответ 3
string path = @"C:\TEXTFILES\";
string path2 = @"P:\myNetworkPath\tesssst";
try
{
Directory.CreateDirectory(path2);
foreach (string fileName in Directory.GetFiles(path))
{
File.Copy(
Path.Combine(path, fileName),
Path.Combine(path2, fileName), true);
}
}
catch
{
Console.WriteLine("Exception");
}
Для более глубокой копии см.:
http://www.codeproject.com/KB/files/copydirectoriesrecursive.aspx
Ответ 4
- Поделитесь своей папкой назначения.
- Есть много способов сделать это. Смотрите следующее:
Скопировать папки в С# с помощью System.IO
Скопировать все содержимое каталога в С#
Ответ 5
Вы найдете все, что вам нужно, в пространстве имен System.IO
и, в частности, в классах File
и Directory
.