public static string GetParentFolder(string path, byte levels = 1, string targetFolder = null) { // Given "C:\Parent\Child\" or "C:\Parent\Child\MyFile.txt", return "C:\Parent". If a target has // been provided, stop when the target folder is found. For example: // GetParentFolder("C:\\one\\two\\three\\four\\five\\test.txt", 50, "three") // returns "C:\\one\\two\\three". string parent = path; levels = MathLibrary.Clamp <byte>(levels, 1, 100); byte level = 0; while ((level < levels) && (parent.Length > 0)) { DirectoryInfo dir = new DirectoryInfo(parent); if (dir.Parent != null) { parent = dir.Parent.FullName; if ((!string.IsNullOrEmpty(targetFolder)) && (parent.EndsWith(targetFolder))) { break; } else { level++; } } else { break; } } return(parent); }
public static string GetRandomString(byte length, bool lettersOnly, bool removeIllegal = false, int seed = 0) { // Generate a randomised string string sRandom = string.Empty; length = MathLibrary.Clamp <byte>(length, 1, 100); // Assign allowed characters to a temporary array byte start, end, character; List <char> allowed = new List <char>(); List <char> forbidden = new List <char>(); if (lettersOnly) { // Lowercase letters only start = 97; // a end = 122; // z } else { // Any printable ASCII character start = 33; // ! end = 126; // ~ // Remove illegal characters? Use if the random string will be used to create a file/folder in // the file system. Forbidden printable ASCII characters are: // * Windows: \ / : * ? " < > | // * MacOS: : // * Linux: / if (removeIllegal) { // Use the Windows superset because it covers MacOS and Linux too forbidden.Add('\\'); forbidden.Add('/'); forbidden.Add(':'); forbidden.Add('*'); forbidden.Add('?'); forbidden.Add('"'); forbidden.Add('<'); forbidden.Add('>'); forbidden.Add('|'); } } if (forbidden.Count > 0) { for (character = start; character <= end; character++) { if (!forbidden.Contains((char)character)) { allowed.Add((char)character); } } } else { for (character = start; character <= end; character++) { allowed.Add((char)character); } } // Create a random number generator (with optional seed for performance and test) Random rnd; if (seed == 0) { Thread.Sleep(1); // Ensure that calls made in close succession have different seeds rnd = new Random(); } else { rnd = new Random(seed); } // Build randomised string for (character = 0; character < length; character++) { sRandom += allowed[rnd.Next(int.MaxValue) % allowed.Count]; } return(sRandom); }