我有一个包含文件的目录 1.TXT 2.txt 3.txt
我怎样才能获得.txt文件名目录中的最高编号?
继承人我试过的事情
DirectoryInfo d = new DirectoryInfo(@"C:\Users\Public\BotMakerLoggerSite\Logs\" + token + @"\");
int highest = 0;
foreach (var file in d.GetFiles(" *.txt"))
{
string a = file.Name.Replace(".txt", "");
int b = Convert.ToInt32(a);
if (b >= highest)
{
highest = b;
}
}
try
{
t = File.ReadAllText(@"C:\Users\Public\BotMakerLoggerSite\Logs\" + token + @"\" + highest + ".txt");
}
catch
{
Console.WriteLine("Error");
}
File.WriteAllText(@"C:\Users\Public\BotMakerLoggerSite\Logs\" + token + @"\" + highest + ".txt", t + Environment.NewLine + e.Source + " | " + DateTime.Now + " | " + e.Severity + " : " + e.Message + "=" + highest);
答案 0 :(得分:0)
这应该有所帮助。它使用正则表达式来提取文件名的数字部分;在这种情况下,它将在文件的开头查找数字,这似乎是您想要的。如果它类似于“my51st.txt”,它将不会返回51.正则表达式部分是行:
Match m = Regex.Match(name, "\\d+");
其中d +表示在字符串的开头提取一个或多个数字。
以下是代码:
var fileNames = Directory.GetFiles(targetDirectory);
var numberList = new List<int>();
int number;
foreach (var name in fileNames) {
Match m = Regex.Match(name, "\\d+"); // this gets the number at beginning of filename
var isNumber = Int32.TryParse(m.ToString(), out number);
if(isNumber)
numberList.Add(number);
}
var highest = numberList.OrderByDescending(x => x).FirstOrDefault();
编辑:重构为更有效的代码,不构建整个数组,然后得到最高的数字。还使用了来自C#7的变量声明:
var fileNames = Directory.GetFiles(targetDirectory);
int? highest = null;
foreach (var name in fileNames) {
var m = Regex.Match(name, "^\\d+"); // this gets the number at beginning of filename
Int32.TryParse(m.ToString(), out int number);
if (number > (highest ?? 0))
highest = number;
}
// The string 'result' will either contain the number or the message depending on whether it is still null or not.
var result = (highest?.ToString() ?? "No Number Found");
答案 1 :(得分:0)
我会用这种方法:
Func<string, int?> tryParse = x =>
{
int r;
if (int.TryParse(x, out r))
{
return r;
}
return null;
};
int highest =
new DirectoryInfo(@"C:\Users\Public\BotMakerLoggerSite\Logs\" + token + @"\")
.GetFiles()
.Select(x => Path.GetFileNameWithoutExtension(x.Name))
.Select(x => tryParse(x))
.Where(x => x.HasValue)
.Select(x => x.Value)
.DefaultIfEmpty(0)
.Max();