以前的答案没有处理网络路径。附加的代码也可以处理。
/// <summary>
/// tests (and creates missing) directories in path containing many
subDirectories which might not exist.
/// </summary>
/// <param name="FN"></param>
public static string VerifyPath(string FN, out bool AllOK)
{
AllOK = true;
var dir = FolderUtils.GetParent(FN);
if (!Directory.Exists(dir))//todo - move to folderUtils.TestFullDirectory
{
const char DIR = '\\';
//string dirDel = "" + DIR;
string[] subDirs = FN.Split(DIR);
string dir2Check = "";
int startFrom = 1;//skip "c:\"
FN = CleanPathFromDoubleSlashes(FN);
if (FN.StartsWith("" + DIR + DIR))//netPath
startFrom = 3;//FN.IndexOf(DIR, 2);//skip first two slashes..
for (int i = 0; i < startFrom; i++)
dir2Check += subDirs[i] + DIR;//fill in begining
for (int i = startFrom; i < subDirs.Length - 1; i++)//-1 for the file name..
{
dir2Check += subDirs[i] + DIR;
if (!Directory.Exists(dir2Check))
try
{
Directory.CreateDirectory(dir2Check);
}
catch { AllOK = false; }
}
}
if (File.Exists(FN))
FN = FolderUtils.getFirstNonExistingPath(FN);
if (FN.EndsWith("\\") && !Directory.Exists(FN))
try { Directory.CreateDirectory(FN); }
catch
{
HLogger.HandleMesssage("couldn't create dir:" + FN, TypeOfExceptions.error, PartsOfSW.FileStructure);
AllOK = false;
}
return FN;
}
还有“CleanDoubleSlashes 函数”:
public static string CleanPathFromDoubleSlashes(string basePath)
{
if (string.IsNullOrEmpty(basePath) || basePath.Length < 2)//don't clean first \\ of LAN address
return basePath;
for (int i = basePath.Length - 1; i > 1; i--)
{
if ((basePath[i] == '\\' && basePath[i - 1] == '\\') || (basePath[i] == '/' && basePath[i - 1] == '/'))
{
basePath = basePath.Remove(i, 1);//Substring(0, i - 2) + basePath.Substring(i, basePath.Length - 1 - i);
}
}
return basePath;
}