开发者

Iterate through Files and pick the closest to my parameter

I'd like to iterate through a folder which can contain files with the following names:

1.xml

2.xml

3.xml

4.xml

etc..

Now I'd like to pick the file that is closest to the number I assign to the searchmethod but not higher than it.

e.g. in the Folder are 1, 3, 5 and 8.xml, my Parameter is 6, I see 6 isn't开发者_开发知识库 there, 8 is too high, pick 5 then!

I've already come across the Directory.GetFiles-Method, but since it returns the whole path this will be a rather nasty string-cutting and -comparing, is there a more elegant solution to my problem? Thanks in advance!


Quick and dirty, with no check to ensure that filenames can actually be parsed to numbers (i.e. if non-numerically named XML files exist, this will fail). Left as an exercise to reader to harden this approach.

Directory.GetFiles(@"C:\somePath" , "*.xml")
.Select(f => new{fn = Path.GetFileNameWithoutExtension(f) , path = f})
.Select(x => new{fileNum = int.Parse(x.fn) , x.path})
.OrderBy(x => x.fileNum)
.TakeWhile(x => x.fileNum <= MYPARAM)
.Select(x => x.path)
.LastOrDefault()


You can use Directory.GetFiles, in conjunction with Path.GetFileNameWithoutExtension(path).

So, something like:

foreach (file in Directory.GetFiles("c:\\temp")) 
{
    int myInt = Int32.Parse(Path.GetFileNameWithoutExtension(file));
}

One LINQ-y solution to your entire problem could be:

int maxFileId = 2;
int myFileNumber = Directory.GetFiles(@"C:\TEMP1\test\EnvVarTest\Testfiles")
    .Select(file => Int32.Parse(Path.GetFileNameWithoutExtension(file)))
    .Where(i => i <= maxFileId)
    .Max();


I'm clearly a slower typer than everyone else :) but i thought I would post it since I had written it.

class Program
{
    public class NumberedXmlFile
    {
        public NumberedXmlFile(string fullPath)
        {
            FullPath = fullPath;
        }
        public string FullPath { get; set; }
        public int FileNumber
        {
            get
            {
                string file = Path.GetFileNameWithoutExtension(FullPath);

                return Convert.ToInt32(file);
            }
        }
    }

    static void Main(string[] args)
    {
        const int targetFileNameNumber = 4;
        const string directoryPathContainingFiles = @"C:\temp";

        IEnumerable<NumberedXmlFile> numberedXmlFiles = Directory.GetFiles(directoryPathContainingFiles).Select(f => new NumberedXmlFile(f));

        NumberedXmlFile theFileIamLookingFor = numberedXmlFiles.OrderBy(f => Math.Abs(f.FileNumber - targetFileNameNumber)).FirstOrDefault();
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜