我正在使用 C# 在 VS2005 中开发一个 Windows 应用程序。在我的项目中,我生成 dll 并将它们存储在一个目录中。这些 dll 将被命名为 TestAssembly1、TestAssembly2、TestAssembly3 等。
所以考虑上面三个dll是否在目录中。下次用户使用我的项目时,我需要生成 TestAssembly4、TestAssembly5 等 dll。
那么如何在文件夹中存储dll的数量,并在下次使用该项目时递增?
该目录甚至可以包含 dll 以外的文件。那么我该怎么做呢?
最佳答案
我个人会使用二进制搜索来查找下一个程序集...
- 开始 n=1
- TestAssembly1.dll 是否存在? (是)
- TestAssembly2.dll 是否存在? (是)
- TestAssembly4.dll 是否存在? (是)
- TestAssembly8.dll 是否存在? (是)
- TestAssembly16.dll 是否存在? (是)
- TestAssembly32.dll 是否存在? (否)
并且在 16 和 32 之间不使用二进制搜索:
- TestAssembly24.dll 是否存在? (是)
- TestAssembly28.dll 是否存在? (是)
- TestAssembly30.dll 是否存在? (否)
- TestAssembly29.dll 是否存在? (是)
所以使用TestAssembly30.dll
这避免了单独保存计数的需要,因此即使您删除了所有文件它也能正常工作——二分查找意味着您的性能不会太差。
未经测试,但如下所示;另请注意,任何 基于文件存在的内容都会立即成为竞争条件(尽管通常非常 slim ):
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);
}
关于c# - 如何将文件的值持久存储在目录中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/909521/