databash
databash

Reputation: 646

Multiple copy from same file

1..1000 | % { copy-Item "C:\path1\test1.xml" "C:\path2\test$_.xml"}

The above PowerShell code copies file from path1 and creates 1000 copies in path2.

How would I recreate this functionality in C# ?

Thanks.

Upvotes: 0

Views: 63

Answers (3)

Moerwald
Moerwald

Reputation: 11254

Something like this:

 System.Linq.Enumerable.Range(1,1000).Select( i => 
     System.IO.File.Copy($"C:\\path1\\test1.xml", $"C:\\path2\\test{i}.xml");

Hope that helps.

Upvotes: 0

Rui Jarimba
Rui Jarimba

Reputation: 17994

Something like this?

using System.IO;

for (int i = 0; i < 1000; i++)
{
    File.Copy(@"C:\path1\test1.xml", $@"C:\path2\test{i}.xml");
}

Note: If the destination file exists, an IOException will be thrown. In that case, you can use the following overload that allows you to overwrite the file:

File.Copy(source, destination, overwrite: true);

Upvotes: 4

blaze_125
blaze_125

Reputation: 2317

for (int i = 0; i < 1000; i++)
{
    System.IO.File.Copy("PathToCopyFrom", $"PathToCopyTo\\{System.IO.Path.GetFileNameWithoutExtension("PathToCopyFrom")}_{i}{System.IO.Path.GetExtension("PathToCopyFrom")}");
}

Upvotes: 0

Related Questions