好的,所以我的程序中有一个文本框,用户可以输入一个值,但是我想在另一个类中调用这个值。
public static void Main()
{
string sourceDirectory = @"F:\RootFolder\testingfolder\Test";
string targetDirectory = @"c:\targetDirectory"; //this is where the value would site
Copy(sourceDirectory, targetDirectory);
}
不是100%肯定如何调用它。 的修改 经过一些急需的研究后,我发现以下内容对我有用;
private void CopyInstallFiles(object sender, EventArgs e)
{
string sourceDirectory = @"F:somepath";
string targetDirectory = directoryImput.Text;
//Copy all the files & Replaces any files with the same name
foreach (string newPath in System.IO.Directory.GetFiles(sourceDirectory, "*.*",
SearchOption.AllDirectories))
File.Copy(newPath, newPath.Replace(sourceDirectory, targetDirectory), true);
答案 0 :(得分:1)
我刚刚意识到你正在寻找一种移动所有文件和文件夹的方法 - 傻我。这里有一些来自https://msdn.microsoft.com/en-us/library/bb762914.aspx的例子:
using System;
using System.IO;
class DirectoryCopyExample
{
static void Main()
{
// Copy from the current directory, include subdirectories.
DirectoryCopy(".", @".\temp", true);
}
private static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
{
// Get the subdirectories for the specified directory.
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
if (!dir.Exists)
{
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ sourceDirName);
}
DirectoryInfo[] dirs = dir.GetDirectories();
// If the destination directory doesn't exist, create it.
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
}
// Get the files in the directory and copy them to the new location.
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
string temppath = Path.Combine(destDirName, file.Name);
file.CopyTo(temppath, false);
}
// If copying subdirectories, copy them and their contents to new location.
if (copySubDirs)
{
foreach (DirectoryInfo subdir in dirs)
{
string temppath = Path.Combine(destDirName, subdir.Name);
DirectoryCopy(subdir.FullName, temppath, copySubDirs);
}
}
}
}
简短版本 - 将其放在DirectoryManager.cs中并通过DirectoryManager.CopyDirectory(源,目标)调用:
using System.IO;
class DirectoryManager
{
internal static void CopyDirectory(string input, string output)
{
DirectoryInfo dir = new DirectoryInfo(input);
if (dir.Exists)
{
DirectoryInfo[] dirs = dir.GetDirectories();
Directory.CreateDirectory(output);
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
string temppath = Path.Combine(output, file.Name);
file.CopyTo(temppath, false);
}
foreach (DirectoryInfo subdir in dirs)
{
string temppath = Path.Combine(output, subdir.Name);
CopyDirectory(subdir.FullName, temppath);
}
}
}
}