Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this questioni have files in c:\MyData for example:
demo.txt
test.ini
COUNT030.flg
COUNT011.flg
COUNT020.flg
COUNT031.flg
COUNT045.flg
COUNT067.flg
i need to take all the files with .flg
Extension and to put the numbers on list like this:
30
11
20
31
45
67
how to do this in C# WinForm ?
thanks in advance
You can use Directory.EnumerateFiles(String, String)
or Directory.GetFiles
method and mask *.flg
. Then use Path.GetFileNameWithoutExtension
to extract file-name without extension, then apply regex \d+$
to match number.
Example:
var result = Directory
.EnumerateFiles(path, "*.flg")
.Select(s => int.Parse(Regex.Match(Path.GetFileNameWithoutExtension(s), @"\d+$").Value));
DirectoryInfo dirInfo = new DirectoryInfo(folderPath);
var numbers = from fileInfo in dirInfo.EnumerateFiles("*.flg")
let fileName = Path.GetFileNameWithoutExtension(fileInfo.Name)
select int.Parse(fileName.Substring("Count".Length, 3));
List<int> lst = numbers.ToList();
So, as promised the sample:
DirectoryInfo di = new DirectoryInfo(@"c:\temp\");
FileInfo[] fis = di.GetFiles("*.flg");
foreach (FileInfo fi in fis)
{
Console.WriteLine("File Name: {0}, Full Name: {1}, Number: {2}", fi.Name, fi.FullName, fi.Name.Substring(fi.Name.LastIndexOf(".") - 3, 3));
}
for extracting the numbers look at the Substring in the sample.
精彩评论