forked from NancyFx/Nancy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPathHelper.cs
More file actions
44 lines (38 loc) · 1.29 KB
/
Copy pathPathHelper.cs
File metadata and controls
44 lines (38 loc) · 1.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
namespace Nancy.Testing
{
using System;
using System.IO;
using System.Linq;
public static class PathHelper
{
/// <summary>
/// Traverses up a directory tree
/// </summary>
/// <param name="path">Start path.</param>
/// <param name="levels">Levels to climb.</param>
/// <returns>A <see cref="string"/> containing the new path.</returns>
public static string GetParent(string path, int levels)
{
if (string.IsNullOrEmpty(path))
{
throw new ArgumentException("path cannot be null or empty", "path");
}
if (levels < 0)
{
throw new ArgumentException("levels cannot be negative", "levels");
}
if (levels == 0)
{
return path;
}
var parts = path.Split(Path.DirectorySeparatorChar);
if (parts.Length <= levels)
{
throw new InvalidOperationException("Cannot go up beyond the root.");
}
return
parts.Take(parts.Length - levels).Aggregate(
(p1, p2) => String.Format("{0}{1}{2}", p1, Path.DirectorySeparatorChar, p2));
}
}
}