根据文件夹中的其他文件命名文件?

时间:2013-09-07 22:12:54

标签: c# file filenames

我有一个文件夹,其文本文件名称如下,例如:0,1,2,3 ...

我需要检查文件名中的最大数字。

例如,如果我有文件1.txt和2.txt以及3.txt,我想得到3。

我怎么能这样做?

谢谢,

3 个答案:

答案 0 :(得分:1)

一些LINQ善良:

var maxNumber = Directory.GetFiles(@"C:\test")
                         .Select(file => Path.GetFileNameWithoutExtension(file))
                         .Where(filename => filename.All(ch => char.IsNumber(ch)))
                         .Select(filename => int.Parse(filename))
                         .Max();

答案 1 :(得分:0)

尝试这样的事情

private static void CreateNewFile()
       {
          string[] files = Directory.GetFiles(@"c:\test");
          int maxNumb = 0;
          foreach (var item in files)
          {
              FileInfo file = new FileInfo(item);
              maxNumb = Math.Max(maxNumb,     int.Parse(Path.GetFileNameWithoutExtension(file.FullName)));
          }
        File.Create(string.Format("{0}.txt", maxNumb++));
       }

希望这个帮助

答案 2 :(得分:0)

听起来像是家庭作业,但现在已经很晚了,所以我心情很好:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            //set the path to check:
            var path = @"D:\Thefiles";
            //create a dictionary to store the results so we can also remember the file name
            var results = new Dictionary<int, string>();
            //loop all the files
            foreach (var file in Directory.GetFiles(path))
            {
                //get the name without any extension
                var namePart = Path.GetFileNameWithoutExtension(file);
                //try to cast it as an integer; if this fails then we can't count it so ignore it
                int fileNumber = 0;
                if (Int32.TryParse(namePart, out fileNumber))
                {
                    //add to dictionary
                    results.Add(fileNumber, file);
                }
            }
            //only show the largest file if we actually have a result
            if (results.Any())
            {
                var largestFileName = results.OrderByDescending(r => r.Key).First();
                Console.WriteLine("Largest name is {0} and the file name is {1}", largestFileName.Key, largestFileName.Value);
            }
            else
            {
                Console.WriteLine("No valid results!");
            }
            Console.ReadLine();
        }
    }
}