我是 C# 新手,無法將 15 天前的所有檔案從一個目錄復制到另一個目錄。這就是我所擁有的。
這只是復制類。
using System;
namespace DeleteOldLogFiles
{
public class Copier
{
public Copier()
{
string sourcePath = @"M:\";
string targetPath = @"L:\";
string fileName = string.Empty;
string destFile = string.Empty;
DateTime fileDate = DateTime.Today.AddDays(-15);
if (System.IO.Directory.Exists(sourcePath))
{
string[] files = System.IO.Directory.GetFiles(sourcePath);
foreach (string s in files)
{
fileName = System.IO.Path.GetFileName(s);
fileDate = DateTime.Today.AddDays(-15);
destFile = System.IO.Path.Combine(targetPath, fileName);
System.IO.File.Copy(s, destFile, true);
}
}
else
{
Console.WriteLine("Error, path does not exist.");
}
}
}
}
uj5u.com熱心網友回復:
無法使用標準System.IO. 但是一旦你有了一份潛在候選人名單,就會有. 選擇適合您需要的時間戳,將其與您的日期限制變數進行比較,并根據比較結果執行/不執行復制。File.GetLastWriteTime() File.GetLastAccessTime() File.GetCreationTime()
不是很清楚,你的意思是什么
復制 15 天前的所有檔案
例如,如果您想復制過去 15 天內創建的所有檔案,您可以執行以下操作:
var limit = DateTime.Today.AddDays(-15);
foreach (string s in files)
{
var creationTime = System.IO.File.GetCreationTime(s);
if (creationTime > limit) { //the file was created within the last 15 days
string fileName = System.IO.Path.GetFileName(s);
string destFile = System.IO.Path.Combine(targetPath, fileName);
System.IO.File.Copy(s, destFile, true);
}
}
如果您的意思是其他內容,請相應地調整比較。
此外,無需在回圈體之外定義fileNameordestFile變數。
而且,您可能需要重新考慮在類建構式中執行此操作。似乎這個類的唯一目的是復制檔案,一旦復制完成,就不需要該類的實體。也許一種static方法會更好......
uj5u.com熱心網友回復:
正如我所看到的,您可以使用FileInfoClass來完成您正在尋找的功能,使用該類您可以執行以下操作:
添加:
using System.IO;
并將您的代碼更改為如下所示:
var fi1 = new FileInfo(s);
if (fi1.CreationTime < fileDate)
{
System.IO.File.Copy(s, destFile, true);
}
uj5u.com熱心網友回復:
您可以使用以下代碼:
string[] getFiles = Directory.GetFiles("your path");
DateTime time = DateTime.Today.AddDays(-15);
foreach (var file in getFiles)
{
FileInfo fileInfo = new FileInfo(file);
if(fileInfo.CreationTime.Day == time.Day)
{
//copy file
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/324517.html
