Onwerk Blog

.NET Framework: Directory- and File-methods trim paths

A generic error occurred in GDI+, that was the very generic error message when using System.Drawing.Image.Save to save an image to a previously created directory.
Further investigations showed that it actually was not an error with Image.Save, which in fact was behaving correctly (let aside the cryptic error message).
The „error“ was not an error per se, but more an unexpected behaviour of the method used to create the directory: Directory.CreateDirectory.
This method has been called erroneously with a path having a space character at the end of one of path specification parts:

private static void Test(Image newImage)
    var dir = @"C:\Space \subdir\";

    var fileName = Path.Combine(dir, "savedImage.png");


    newImage.Save(fileName, ImageFormat.Jpeg);

The previous code instructs the framework to create a path „Space “ (with trailing space) under „C:\“. Instead a directory „Space“ (without trailing space) is created, this can be checked with Windows Explorer or the command line.
Although it makes sense to trim the single parts of a path it is still somewhat unexpected and may lead to undesired effects
We checked some more Directory and File class methods and at least those we check have all the same behaviour.

geschrieben von onwerk am 23. November 2016 um 15:44

Nach oben
Zur Desktop-Version