我需要使用不包含完整信息的文本文件从目录中复制多个文件。
NCR.txt:
红色
目标目录中有:
red1.txt
red3.txt
red44.txt
目录需要有:
red1.txt
red3.txt
red44.txt
我的代码:
System.IO.Directory.CreateDirectory(@"C:\nPrep\" + textBox1.Text + "\\red");
if (checkBox3.Checked)
{
String[] file_names = File.ReadAllLines(@"C:\NCR.txt");
foreach (string file_name in file_names)
{
string[] files = Directory.GetFiles(textBox2.Text, file_name + "*.txt");
foreach (string file in files)
System.IO.File.Copy(file, @"C:\nPrep\" + textBox1.Text + "\\red\\");
}
}
答案 0 :(得分:13)
//FileInfo & DirectoryInfo are in System.IO
//This is something you should be able to tweak to your specific needs.
static void CopyFiles(DirectoryInfo source,
DirectoryInfo destination,
bool overwrite,
string searchPattern)
{
FileInfo[] files = source.GetFiles(searchPattern);
//this section is what's really important for your application.
foreach (FileInfo file in files)
{
file.CopyTo(destination.FullName + "\\" + file.Name, overwrite);
}
}
此版本更准备好复制粘贴:
static void Main(string[] args)
{
DirectoryInfo src = new DirectoryInfo(@"C:\temp");
DirectoryInfo dst = new DirectoryInfo(@"C:\temp3");
/*
* My example NCR.txt
* *.txt
* a.lbl
*/
CopyFiles(src, dst, true);
}
static void CopyFiles(DirectoryInfo source, DirectoryInfo destination, bool overwrite)
{
List<FileInfo> files = new List<FileInfo>();
string[] fileNames = File.ReadAllLines("C:\\NCR.txt");
foreach (string f in fileNames)
{
files.AddRange(source.GetFiles(f));
}
if (!destination.Exists)
destination.Create();
foreach (FileInfo file in files)
{
file.CopyTo(destination.FullName + @"\" + file.Name, overwrite);
}
}
答案 1 :(得分:2)
所有建议都很棒,感谢所有的建议,但这很完美:
if (checkBox3.Checked)
{
string[] lines = File.ReadAllLines(@"C:\NCR.txt");
foreach (string line in lines)
{
string[] files = Directory.GetFiles(textBox2.Text, line + "*.txt");
foreach (string file in files)
{
FileInfo file_info = new FileInfo(file);
File.Copy(file, @"C:\InPrep\" + textBox1.Text + "\\text\\" + file_info.Name);
}
}
}
答案 2 :(得分:0)
string sourceDir = @"c:\";
string destDir = @"c:\TestDir";
var r = Directory.GetFiles(sourceDir, "red*.txt"); //Replace this part with your read from notepad file
foreach (var s in r)
{
var sourceFile = new FileInfo(s);
sourceFile.CopyTo(destDir + "\\" + s.Replace(sourceDir, string.Empty));
}