开发者

.NET: System.IO.Path

Given a string that is to a directory, how can I make sure there's a closing \ character? For example,开发者_如何学运维 C:\foo is a directory, and so is C:\foo\. Is there a System.IO.Path method that ensures there's a ending \?


if (!filename.EndsWith(Path.DirectorySeparatorChar))
    filename += Path.DirectorySeparatorChar;


Presumably you want to append a separator so that you can subsequently append filenames using string concatenation.

In which case Kyle Rozendo's initial advice is sound: consider whether you really need to do that. If you always append filenames using Path.Combine, you don't need to care whether your path has a trailing separator.

If you still want to do this, you have an edge case to consider. The path "D:" is a valid relative path that references the current working directory on the D: drive. Appending a separator will change this meaning to reference the root directory on the D: drive. Do you really want this? I'm guessing not. So I would special case this thus:

public static string AppendSeparator(string path)
{
    if (path == null) throw new ArgumentNullException("path");
    if (path.Length == 0) return path;
    if (path[path.Length - 1] == Path.VolumeSeparatorChar) return path;
    if (path[path.Length - 1] == Path.DirectorySeparatorChar) return path;
    if (path[path.Length - 1] == Path.AltDirectorySeparatorChar) return path;
    return path + Path.DirectorySeparatorChar;
}

You can then use this as follows - the last example converts the input path to an absolute path before appending the separator:

path = AppendSeparator(@"C:\SomePath\");
path = AppendSeparator(@"C:\SomePath");
path = AppendSeparator(@"D:");
path = AppendSeparator(Path.GetFullPath("D:"));


Hay, what about using this condition

if (s.IndexOf('\\') == s.Length - 1)

where s is your path string "amr\" will give true "amr" will give false


I think you need to write a custom path class.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜