How to store values persistenly of files in a directory?

后端 未结 3 708
小蘑菇
小蘑菇 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:02

    Personally I'd use a binary search to find the next assembly...

    • start n=1
    • does TestAssembly1.dll exist? (yes)
    • does TestAssembly2.dll exist? (yes)
    • does TestAssembly4.dll exist? (yes)
    • does TestAssembly8.dll exist? (yes)
    • does TestAssembly16.dll exist? (yes)
    • does TestAssembly32.dll exist? (no)

    and no use binary search between 16 and 32:

    • does TestAssembly24.dll exist? (yes)
    • does TestAssembly28.dll exist? (yes)
    • does TestAssembly30.dll exist? (no)
    • does TestAssembly29.dll exist? (yes)

    so use TestAssembly30.dll

    This avoids the need to keep the count separately, so it'll work even if you delete all the files - and the binary search means you don't have too bad performance.

    Untested, but something like below; also note that anything based on file existence is immediately a race condition (although usually a very slim one):

        static string GetNextFilename(string pattern) {
            string tmp = string.Format(pattern, 1);
            if (tmp == pattern) {
                throw new ArgumentException(
                     "The pattern must include an index place-holder", "pattern");
            }
            if (!File.Exists(tmp)) return tmp; // short-circuit if no matches
    
            int min = 1, max = 2; // min is inclusive, max is exclusive/untested
            while (File.Exists(string.Format(pattern, max))) {
                min = max;
                max *= 2;
            }
    
            while (max != min + 1) {
                int pivot = (max + min) / 2;
                if (File.Exists(string.Format(pattern, pivot))) {
                    min = pivot;
                }
                else {
                    max = pivot;
                }
            }
            return string.Format(pattern, max);
        }
    

提交回复
热议问题