2009-05-26 27 views
4

我正在使用C#在VS2005中開發Windows應用程序。在我的項目中,我生成了dll並將它們存儲在一個目錄中。這些dll將命名爲TestAssembly1,TestAssembly2,TestAssembly3等。如何存儲目錄中文件的持久性值?

因此,請考慮上述三個dll是否在目錄中。下次用戶使用我的項目時,我需要生成如TestAssembly4,TestAssembly5等DLL。

那麼如何在存儲文件夾中存儲dll的數量並在下次使用項目時增加它們呢?

該目錄甚至可以包含dll以外的文件。那我該怎麼做?

回答

10

個人而言,我會使用二進制搜索尋找下一個組件。 ..

  • 開始n = 1的
  • 確實TestAssembly1.dll存在嗎? (是)
  • TestAssembly2.dll是否存在? (是)
  • TestAssembly4.dll是否存在? (是)
  • TestAssembly8.dll存在嗎? (是)
  • TestAssembly16.dll是否存在? (是)
  • TestAssembly32.dll是否存在? (無)

和16和32之間沒有使用二進制搜索:

  • 確實TestAssembly24.dll存在嗎? (是)
  • TestAssembly28.dll存在嗎? (是)
  • TestAssembly30.dll存在嗎? (no)
  • TestAssembly29.dll是否存在? (是)

所以使用TestAssembly30.dll

這避免了需要單獨保留計數,所以它甚至會工作,如果你刪除所有文件 - 和二進制搜索意味着你不這樣做表現太差。

未經測試,但如下所示;還注意到,根據文件存在什麼立即是一個競爭條件(儘管通常是非常渺茫的一個):

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); 
    } 
+0

這取決於問題域。你需要特別處理差距嗎?在正常情況下,你希望只有少數文件存在於目錄中。(在一個目錄中獲得完整的文件列表要比同樣數量的file.exist操作便宜得多) – 2009-05-26 08:21:20

1

而是很多檢查,如果文件已經存在,你可以得到所有組件的列表,提取其ID並返回最高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 ExtractIdsFromAssemblyList(files, regexPattern) 
      .Max() + 1; 
} 

private IEnumerable<int> 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; 
      } 
     } 
    } 
} 
相關問題