private static async Task ServeDirectoryListingAsync(DirectoryInfo root, DirectoryInfo directory, HttpListenerResponse response) { StringBuilder listBuilder = new StringBuilder(); foreach (FileInfo file in directory.EnumerateFiles()) { String target = directory.IsSameDirectory(root) ? file.Name : Path.Combine(directory.Name, file.Name); listBuilder.AppendFormat("<li><a href=\"{0}\">{1}</a></li>", target, file.Name); } foreach (DirectoryInfo subDirectory in directory.EnumerateDirectories()) { String target = directory.IsSameDirectory(root) ? subDirectory.Name : Path.Combine(directory.Name, subDirectory.Name); listBuilder.AppendFormat("<li><a href=\"{0}\">{1}</a></li>", target, subDirectory.Name); } String htmlResponse = String.Format("<ul>{0}</ul>", listBuilder.ToString()); response.ContentType = "text/html"; response.ContentLength64 = htmlResponse.Length; response.AddHeader("Date", DateTime.Now.ToString("r")); response.StatusCode = (Int32)HttpStatusCode.OK; // Must be set before writing to OutputStream. using (StreamWriter writer = new StreamWriter(response.OutputStream)) { await writer.WriteAsync(htmlResponse).ConfigureAwait(false); } }
/// <summary> /// Returns true when childFolder is a subfolder of parentFolder /// </summary> /// <param name="childFolder"></param> /// <param name="parentFolder"></param> /// <returns></returns> public static bool IsChildFolder(DirectoryInfo childFolder, DirectoryInfo parentFolder) { if (childFolder.Parent == null) return false; childFolder = childFolder.Parent; if (childFolder.IsSameDirectory(parentFolder)) return true; return IsChildFolder(childFolder, parentFolder); }