2011-03-26 46 views
1

如果我有4个文件。和我想如果即时通讯使用到其中的一半移动到盘1和其中一半到盘2将一半的文件复制到一个地方,另一半复制到其他c#

Directory.Move(source, destination) 即时猜测我可以通过执行一个foreach循环+数组或列表改变为源, 但是如何在一半的源文件被转移之后改变目的地,然后将另一半转移到新的目的地?

回答

2
string[] files = ... // create a list of files to be moved 
for (int i = 0; i < files.Length; i++) 
{ 
    var sourceFile = files[i]; 
    var destFile = string.Empty; 
    if (i < files.Length/2) 
    { 
     destFile = Path.Combine(@"c:\path1", Path.GetFileName(sourceFile)); 
    } 
    else 
    { 
     destFile = Path.Combine(@"d:\path2", Path.GetFileName(sourceFile)); 
    } 
    File.Move(sourceFile, destFile); 
} 

UPDATE:

这里有一个偷懒的办法不需要您一次它可用于例如结合Directory.EnumerateFiles方法加载在内存中的所有文件名:

IEnumerable<string> files = Directory.EnumerateFiles(@"x:\sourcefilespath"); 
int i = 0; 
foreach (var file in files) 
{ 
    var destFile = Path.Combine(@"c:\path1", Path.GetFileName(file)); 
    if ((i++) % 2 != 0) 
    { 
     // alternate the destination 
     destFile = Path.Combine(@"d:\path2", Path.GetFileName(file)); 
    } 
    File.Move(sourceFile, destFile); 
} 
+0

或者你可以使用'如果(我%2 == 0)' – Hogan 2011-03-26 22:58:21

+0

@Hogan,是的,这也将工作,这只是它会交替,以及如果存在的秩序观念在最初的文件集合中可能不合适。 – 2011-03-26 23:00:19

+0

@Darin:这种方法虽然可以使用普通枚举,所以您不必将完整列表加载到内存中 - 取决于OP的需求(在重新阅读这个问题之后,我认为它看起来像是过度杀伤了) – BrokenGlass 2011-03-26 23:07:51

0

简单的答案是,您将移动单个文件。

使用Directory.GetFiles(source)获取文件夹中的文件列表,获取该文件的.Count(),然后遍历每个文件并将其移动。

public void MoveFilesToSplitDestination(string source, string destination1, string destination2) 
{ 
    var fileList = Directory.GetFiles(source); 
    int fileCount = fileList.Count(); 

    for(int i = 0; i < fileCount; i++) 
    { 
     string moveToDestinationPath = (i < fileCount/2) ? destination1 : destination2; 
     fileList[i].MoveTo(moveToDestination); 
    } 
} 
0
int rubikon= files.Count()/2; 
foreach (var file in files.Take(rubikon)) 
    file.Move(/* first destination */)); 
foreach (var file in files.Skip(rubikon)) 
    file.Move(/* second destination */)); 
+0

好的答案......现在我们需要的是一个叫做'rubikon()'的函数在循环之间交叉。 – Hogan 2011-03-27 01:14:54

相关问题