Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/334.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何将最新文件从一个目录复制到另一个目录_C#_File Io - Fatal编程技术网

C# 如何将最新文件从一个目录复制到另一个目录

C# 如何将最新文件从一个目录复制到另一个目录,c#,file-io,C#,File Io,大家好,我还是C#的新手,我在C:\SourceFolder的目录中有一些文件,这些文件与文件名为_yyymmdd格式的日期字符串连接在一起 这: 我只想将最长日期的文件(例如(report_20130228.text)复制到另一个目录,请查看代码,但它会复制所有文件。我做得不对吗 class Program { static void Main(string[] args) { Program copy = new Program(); Dire

大家好,我还是C#的新手,我在C:\SourceFolder的目录中有一些文件,这些文件与文件名为_yyymmdd格式的日期字符串连接在一起 这:

我只想将最长日期的文件(例如(report_20130228.text)复制到另一个目录,请查看代码,但它会复制所有文件。我做得不对吗

class Program
{
    static void Main(string[] args)
    {
        Program copy = new Program();
        DirectoryInfo sourcedinfo = new DirectoryInfo(@"C:\Users\Input");
        DirectoryInfo destinfo = new DirectoryInfo(@"C:\Users\Output");

        copy.CopyAll(sourcedinfo, destinfo);
        Console.Read();
    }
    public void CopyAll(DirectoryInfo source, DirectoryInfo target)
    {
        try
        {
            //check if the target directory exists
            if (Directory.Exists(target.FullName) == false)
            {
                Directory.CreateDirectory(target.FullName);
            }

            //copy all the files into the new directory

            foreach (FileInfo fi in source.GetFiles())
            {
                Console.WriteLine(@"Copying {0}\{1}", target.FullName, fi.Name);

                  fi.CopyTo(Path.Combine(target.ToString(), fi.Name), true);
            }

            Console.WriteLine("Success");
        }
        catch (IOException ie)
        {
            Console.WriteLine(ie.Message);
        }
    }
}

我已经根据创建时间对列表进行了排序并选择了它。有可能你必须检查和改变它,但只是次要的

public void CopyAll(DirectoryInfo source, DirectoryInfo target)
{
    try
    {
        //check if the target directory exists
        if (Directory.Exists(target.FullName) == false)
        {
            Directory.CreateDirectory(target.FullName);
        }

        //copy all the files into the new directory
        // Modified from here
            DateTime latestDate = source.GetFiles().Max(x => DateTime.ParseExact(x.Name.Substring(x.Name.IndexOf('_') + 1), "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture));

           FileInfo fileInfo = source.GetFiles().Single(x => x.Name == "report_" + latestDate.ToString("yyyyMMdd") + ".text");

            Console.WriteLine(@"Copying {0}\{1}", target.FullName, fileInfo.Name);

              fileInfo.CopyTo(Path.Combine(target.ToString(), fileInfo.Name), true);
        //ends here

        Console.WriteLine("Success");
    }
    catch (IOException ie)
    {
        Console.WriteLine(ie.Message);
    }
}
选择最后一个文件(如果文件名没有点或下划线则有效):

IEnumerable lastFiles=
source.EnumerateFiles()
.选择(f=>new{
File=f,
Name=f.Name.Split(“”“)[0],
Date=DateTime.ParseExact(f.Name.Split(“”,‘.)[1],“yyyyymmdd”,
CultureInfo.InvariantCulture)
})
.GroupBy(x=>x.Name)
.Select(g=>g.OrderByDescending(x=>x.Date).First().File);
然后复制软管文件


如果文件名可能包含点或下划线,则使用正则表达式提取名称和日期:

IEnumerable<FileInfo> lastFiles = 
 source.EnumerateFiles()
       .Select(f => {
           Match match = Regex.Match(f.Name, @"(?<name>.+)_(?<date>\d{8})\.\w+");
           return new {
              File = f,
              Name = match.Groups["name"].Value,
              Date = DateTime.ParseExact(match.Groups["date"].Value, "yyyyMMdd",
                                         CultureInfo.InvariantCulture) 
           };
        })
       .GroupBy(x => x.Name)
       .Select(g => g.OrderByDescending(x => x.Date).First().File);
IEnumerable lastFiles=
source.EnumerateFiles()
.选择(f=>{
Match Match=Regex.Match(f.Name,@“(?。+)\u(?\ d{8})\.\w+”;
还新{
File=f,
名称=匹配。组[“名称”]。值,
Date=DateTime.ParseExact(match.Groups[“Date”].Value,“yyyyymmdd”,
CultureInfo.InvariantCulture)
};
})
.GroupBy(x=>x.Name)
.Select(g=>g.OrderByDescending(x=>x.Date).First().File);

您不会在任何地方过滤文件列表……而且您对源位置的描述与代码不匹配……该方法称为CopyAll(),您会问为什么它会复制所有文件?我假设你在什么地方找到了这段代码?这就是为什么我明确表示我是C#新手,谢谢你的帮助,至少我尝试了一些方法,我认为当报表的创建日期大于报表的创建日期时,这会产生问题,因为我想要最大日期,我得到了你的观点,但在一般情况下,我认为这不会发生。新的一天,我将修改代码,非常感谢您,但是这会给System.Invalid.OperationException FileInfo FileInfo=source.GetFiles().Single(x=>x.Name==“report_uuu“+latestDate.ToString(“yyyyMMdd”)+“.text”);检查最新发布的内容。它的值是否正确?FileInfo myFile=source.GetFiles().Single(i=>i.Name==“report_”+myFileDate.ToString(“yyyyMMdd”)+“.text”);这是一个零例外。这就像一颗炸弹,非常感谢你-懒散的别列佐夫斯基
IEnumerable<FileInfo> lastFiles = 
 source.EnumerateFiles()
       .Select(f => new {
            File = f,
            Name = f.Name.Split('_')[0],
            Date = DateTime.ParseExact(f.Name.Split('_', '.')[1], "yyyyMMdd",
                                       CultureInfo.InvariantCulture)
       })
       .GroupBy(x => x.Name)
       .Select(g => g.OrderByDescending(x => x.Date).First().File);
IEnumerable<FileInfo> lastFiles = 
 source.EnumerateFiles()
       .Select(f => {
           Match match = Regex.Match(f.Name, @"(?<name>.+)_(?<date>\d{8})\.\w+");
           return new {
              File = f,
              Name = match.Groups["name"].Value,
              Date = DateTime.ParseExact(match.Groups["date"].Value, "yyyyMMdd",
                                         CultureInfo.InvariantCulture) 
           };
        })
       .GroupBy(x => x.Name)
       .Select(g => g.OrderByDescending(x => x.Date).First().File);
DateTime myFileDate = source.GetFiles().Max(i => DateTime.ParseExact(i.Name.Substring(7, 8), "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture));
FileInfo myFile = source.GetFiles().Single(i => i.Name == "report_" + myFileDate.ToString("yyyyMMdd") + ".text");
myFile.CopyTo(Path.Combine(target.ToString(), myFile.Name), true);