Поделиться через


.NET API's are not always honest

First a quiz, assuming that all required priviledges are there what is the output of the following code. All the important bits are marked in bold

 class Program{static void Main(string[] args){    string dirName =  @"c:\a." ;    try    {        System.IO.Directory.CreateDirectory(dirName);          Console.WriteLine("Created {0}", dirName);        Console.WriteLine( System.IO.Directory .Exists(dirName)  ?                             "Dir exist": "Dir doesn't exist");    }    catch (Exception ex)    {        Console.WriteLine("Failed to create directory {0}: {1}", 
                           dirName, ex.Message);    }}

The output is

Created c:\a.
Dir exist

The problem is if I go to C:\ I see a folder names a and not a. The dot at the end is conveniently dropped. What more interesting is that even though a. does not exist the Directory.Exists API returns true. Windows does not support files and folders with a dot at the end. If you use command window to create a file with a dot at the end then you simply get the file without the dot and no error is reported. .NET Directory API's exactly simulate this, but the question is do I want the simulation? I'd like to see API's being honest and report issues if it fails to do something. API's are used at a lot of places and the burden of checking should be done inside the API and not on code calling the API.

In VSTS we just got hit by a bug due to this. When you create a Build Type using the the Wizard, the user can enter names with a DOT at the end. We then create a folder with that name and check the whole thing into Team Foundation Source Control. The problem is what gets created is a and not a. So even though you wanted to create a Build Type named a.  you have one named a and all sorts of weird things happen after that. Though this is kind-of a corner situation but still I'd prefer a more honest API anyday.....

Comments

  • Anonymous
    January 18, 2006
    Cann't believe... I just know it!
  • Anonymous
    January 24, 2006
    I don't think you have much choice in the matter. This behavior is not simulated, it is created by the Win32 layer. The only way to avoid it is to create your files/directories by calling NtCreateFile, and still it would likely only work on NTFS volumes.

    You should then be able to create directories that have a space or period at the end, differ only by case, and possibly even include characters such as asterisks, colons, and nuls. Of course you would end up with files and directories that could not be opened or deleted from most Windows programs (like Explorer), so it would be quite a useless venture.

    I think the best thing to do is just filter the names for trailing spaces and periods before passing them to filesystem functions.
  • Anonymous
    January 25, 2006
    The comment has been removed