我无法让我的类从program.cs运行到form.cs,当我请求它时。我已经尝试了数字方法,但它们似乎不起作用,我使用了我用来在两个文件之间发送变量的方法,但是没有用,我搜索但不明白代码是什么做或在哪里放。我想要它做的是在backgroundworker中运行该类,但我之前显示的变量方法对该类不起作用。
这是我想要运行的课程
public static class DirectoryInfoExtensions
{
//Copies all files from one directory to another.
public static void CopyTo(this DirectoryInfo source, string destDirectory, bool recursive)
{
if (source == null)
throw new ArgumentNullException("source");
if (destDirectory == null)
throw new ArgumentNullException("destDirectory");
// If the source doesn't exist, we have to throw an exception.
if (!source.Exists)
throw new DirectoryNotFoundException("Source directory not found: " + source.FullName);
// Compile the target.
DirectoryInfo target = new DirectoryInfo(destDirectory);
//If the target doesn't exist, we create it.
if (!target.Exists)
target.Create();
// Get all files and copy them over.
foreach (FileInfo file in source.GetFiles())
{
file.CopyTo(Path.Combine(target.FullName, file.Name), true);
}
// Return if no recursive call is required.
if (!recursive)
return;
// Do the same for all sub directories.
foreach (DirectoryInfo directory in source.GetDirectories())
{
CopyTo(directory, Path.Combine(target.FullName, directory.Name), recursive);
}
}
}
这是我想在form.cs中运行它的地方
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
}
答案 0 :(得分:1)
您只想运行CopyTo方法?这应该很容易。您可以显式调用它:
DirectoryInfoExtensions.CopyTo(source, "C:\DestinationDirectory", true);
...或作为扩展方法:
source.CopyTo("C:\DestinationDirectory", true);
当然,如果您的扩展名与表单类不在同一名称空间中,则需要确保使用DirectoryInfoExtensions所在的命名空间,方法是将以下内容放在文件的顶部:
using Utilities; // replace Utilities with whatever namespace DirectoryInfoExtensions is in
你需要有一个类型为DirectoryInfo的source
变量。
var source = new DirectoryInfo("C:\SourceDirectory");
答案 1 :(得分:0)
这应该有效:
DirectoryInfo.CopyTo("<source folder>, "<target folder>", true)
这样做不行吗?你看到什么错误?