我有一个包含这样命名的文本文件的文件夹,例如:0、1、2、3...
我需要检查文件名中的最高数字。
例如,如果我有文件 1.txt 和 2.txt 和 3.txt,我想得到 3。
我怎么能那样做?
谢谢,
一些 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();
尝试这样的事情
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++));
}
希望这有帮助
听起来像是功课,但已经很晚了,我心情很好,所以:
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();
}
}
}