Use Path class instead of string manipulations

пятница, 25 июля 2008 г. ·

Today i've found such a code in my project. This code was added by other developer. The interesting thing about this code is bold line:


private static string GetFullPath(string directoryPath, string fileName)
{
if (string.IsNullOrEmpty(directoryPath))
throw new ArgumentOutOfRangeException("directoryPath");
if (string.IsNullOrEmpty(fileName))
throw new ArgumentOutOfRangeException("fileName");

return string.Format("{0}\\{1}", directoryPath.Trim('\\'), fileName);
}

What is wrong? If you want to be sure that path will be constructed properly use Path class and it static methods. Here is how this code should look like:

      private static string GetFullPath(string directoryPath, string fileName)
{
if (string.IsNullOrEmpty(directoryPath))
throw new ArgumentOutOfRangeException("directoryPath");
if (string.IsNullOrEmpty(fileName))
throw new ArgumentOutOfRangeException("fileName");

return Path.Combine(directoryPath, fileName);
}

Conclusion: Use Path class for file path manipulations instead of string manipulations

Обо мне

Моя фотография
Кто к нам с чем и зачем, тот от того и того!