How to store values persistenly of files in a directory?

后端 未结 3 711
小蘑菇
小蘑菇 2021-01-12 18:27

I\'m developing a Windows application in VS2005 using C#. In my project, I generate dlls and store them in a directory. The dlls will be named as TestAssembly1, TestAssembly

3条回答
  •  清歌不尽
    2021-01-12 19:01

    Instead of lots of checking if a file already exist you can get a list of all assemblies, extract their ID's and return the highest ID + 1:

    int nextId = GetNextIdFromFileNames(
                   "pathToAssemblies", 
                   "TestAssembly*.dll", 
                   @"TestAssembly(\d+)\.dll");
    
    [...]
    
    public int GetNextIdFromFileNames(string path, string filePattern, string regexPattern)
    {
        // get all the file names
        string[] files = Directory.GetFiles(path, filePattern, SearchOption.TopDirectoryOnly);
    
        // extract the ID from every file, get the highest ID and return it + 1
        return ExtractIdsFromFileList(files, regexPattern)
               .Max() + 1;
    }
    
    private IEnumerable ExtractIdsFromFileList(string[] files, string regexPattern)
    {
        Regex regex = new Regex(regexPattern, RegexOptions.IgnoreCase);
    
        foreach (string file in files)
        {
            Match match = regex.Match(file);
            if (match.Success)
            {
                int value;
                if (int.TryParse(match.Groups[1].Value, out value))
                {
                    yield return value;
                }
            }
        }
    }
    

提交回复
热议问题