[英]C# Copy User Defined Number of Files
我試圖將一組文件從一個目錄復制到另一個目錄。 我的代碼處於當前狀態,將復制目錄中的所有文件。 我相信我需要一個列表或一個數組,但是對於C#來說有些陌生,所以想在這里提出我的問題。 一個示例是從代碼中指定的目錄中復制20個文件。 任何幫助,將不勝感激。 謝謝!
static void Main(string[] args)
{
}
private void CopyFiles(int numberOfFiles)
{
List<string> files = System.IO.Directory.GetFiles(@"C:\Users\acars\Desktop\A", "*").ToList();
IEnumerable<string> filesToCopy = files.Where(file => file.Contains("Test_Test")).Take(20);
foreach (string file in filesToCopy)
{
// here we set the destination string with the file name
string destfile = @"C:\Users\acars\Desktop\B\" + System.IO.Path.GetFileName(file);
// now we copy the file to that destination
System.IO.File.Copy(file, destfile, true);
};
經過一些修改,您的代碼就能復制給定數量的文件。 以下示例從您的目錄中獲取前x個文件:
private void CopyFiles(int numberOfFiles)
{
List<string> files = System.IO.Directory.GetFiles(@"C:\Users\rando\Desktop\A", "*").ToList();
IEnumerable<string> filesToCopy = files.Where(file => file.Contains("Test_Test")).Take(numberOfFiles);
foreach (string file in filesToCopy)
{
// here we set the destination string with the file name
string destfile = @"C:\Users\rando\Desktop\B\" + System.IO.Path.GetFileName(file);
// now we copy the file to that destination
System.IO.File.Copy(file, destfile, true);
}
}
如果要按特殊順序訂購前x個文件,則必須先訂購“文件”列表。
由於您需要按名稱以外的文件信息進行排序,因此需要使用FileInfo
。 我認為這是一個應該讓您入門的簡單實現。
static void Main(string[] args)
{
var desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
var path = Path.Combine(desktop, "A");
var outPath = Path.Combine(desktop, "B");
Copy(20, "file", path, outPath, x => x.LastWriteTimeUtc);
}
static void Copy<T>(int count, string filter, string inputPath, string outputPath, Func<FileInfo, T> order)
{
new DirectoryInfo(inputPath).GetFiles()
.OrderBy(order)
.Where(file => file.Name.Contains(filter))
.Take(count)
.ToList()
.ForEach(file => File.Copy(file.FullName, Path.Combine(outputPath, file.Name), true));
}
要使用此功能,您需要輸入要復制的數字,路徑,過濾器和排序動作。
new DirectoryInfo(inputPath).GetFiles()
-獲取指定路徑中每個文件的FileInfo[]
.OrderBy(order)
-訂購他們 .Where(file => file.Name.Contains(filter))
-通過傳入的過濾器進行過濾 .Take(count)
-計數 .ToList()
-轉換為List以使用ForEach .ForEach(file => File.Copy(file.FullName, Path.Combine(outputPath, file.Name), true))
-對每個文件調用File.Copy()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.