tags:

views:

155

answers:

4

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 \?

A: 

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

amr osama
That will work for all cases except a zero-length string.
Robert Harvey
IndexOf gives the first apperance of the searched string, quite likely the one after the drive.
Wilhelm
You should rather use s.EndsWith or s.LastIndexOf. But EndsWith will work with zero-length strings.
Majkel
You should ideally check for Path.DirectorySeparatorChar and Path.AltDirectorySeparatorChar rather than a hardwired backslash.
Joe
+4  A: 
if (!filename.EndsWith(Path.DirectorySeparatorChar))
    filename += Path.DirectorySeparatorChar;
Jason Williams
You might also want to check for Path.AltDirectorySeparatorChar
Joe
+2  A: 

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:"));
Joe