How to navigate a few folders up?

前端 未结 11 2309
感动是毒
感动是毒 2020-11-29 20:52

One option would be to do System.IO.Directory.GetParent() a few times. Is there a more graceful way of travelling a few folders up from where the executing assembly resides?

11条回答
  •  生来不讨喜
    2020-11-29 21:34

    I have some virtual directories and I cannot use Directory methods. So, I made a simple split/join function for those interested. Not as safe though.

    var splitResult = filePath.Split(new[] {'/', '\\'}, StringSplitOptions.RemoveEmptyEntries);
    var newFilePath = Path.Combine(filePath.Take(splitResult.Length - 1).ToArray());
    

    So, if you want to move 4 up, you just need to change the 1 to 4 and add some checks to avoid exceptions.

提交回复
热议问题