[英]copying files from one folder to another only if their file name is a in a specified text file c#
I need to copy files from one folder to another but only if their file name is also in a text file. 我需要将文件从一个文件夹复制到另一个文件夹,但前提是它们的文件名也位于文本文件中。 The text file is set up like so
文本文件设置如下
file1.jpg
file2.jpg
file3.jpg
etc
There are around one-million files to copy. 有大约一百万个文件要复制。 I'm using C#.
我正在使用C#。
What would the best way to go about this be? 最好的方法是什么? I'm not sure if I should first read all the file names from the text file and put them in to a list then possibly convert the list in to an array then maybe use the array somehow?
我不确定是否应该先从文本文件中读取所有文件名,然后将它们放入列表中,然后将列表转换为数组,然后以某种方式使用该数组? Or maybe there's a better way to go about it?
也许有更好的方法可以解决?
I know how to read and write to files and how to copy from one source destination to another. 我知道如何读写文件,以及如何从一个源目标复制到另一个源目标。 I don't know how to filter out specific files when copying from one source destination to another though.
我不知道从一个源目标复制到另一个目标时如何过滤掉特定文件。
Any help is greatly appreciated. 任何帮助是极大的赞赏。
Thank you. 谢谢。
The following code will help you the process you want 以下代码将帮助您所需的过程
string source = @"C:\SourcePath\";
string destination = @"C:\DestinationPath\";
string[] strFiles = File.ReadAllText(@"C:\Filename.txt").Split(' ');
for (int i = 0; i < strFiles.Length; i++)
{
File.Copy(source + strFiles[i], destination + strFiles[i]);
}
If the text file is one line with million files name. 如果文本文件是具有百万个文件名的一行。 Use this
用这个
string from = @"c:\from" , to =@"d:\to"; // source and destination
StreamReader file = new StreamReader(@"c:\list.txt"); // your files list
string total=file.ReadLine();
string[] tobecopied = total.Split(' ');
foreach(string fil in tobecopied)
{
if(File.Exists(from+@"\"+fil))
{
File.Copy(from+@"\"+fil,to+@"\"+fil);
}
else
{
MessageBox.Show(fil+"Not found ");
}
}
But if the text file have 1 line per 1 file , for example 但是如果文本文件每1个文件有1行,例如
FIle1.exe FIle1.exe
File2.exe File2.exe
use this 用这个
string from = @"c:\from" , to =@"d:\to"; // source and destination
StreamReader file = new StreamReader(@"c:\list.txt"); // your files list
string total="";
string temp="";
while((temp=file.ReadLine())!=null)
{
total+=temp+" ";
}
string[] tobecopied = total.Split(' ');
foreach(string fil in tobecopied)
{
if(File.Exists(from+@"\"+fil))
{
File.Copy(from+@"\"+fil,to+@"\"+fil);
}
else
{
MessageBox.Show(fil+"Not found ");
}
}
These ways also check for file existance. 这些方式还检查文件是否存在。
Hope it works. 希望它能工作。 If someone see error please edit it.
如果有人看到错误,请对其进行编辑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.