views:

80

answers:

2

I have a ListView that displays error to the user. Part of it also includes the exception message. The error is also written to a log file.

Now I have noticed that some exception messages end with a newline. e.g. File.Move can return the message (English .Net 3.5 SP1) "Cannot create a file when that file already exists.\r\n".

The newline causes the listview and logfiles to look strange. Adding a .Trim() fixes the problem but is there a reason for the newline.

+2  A: 

I think that error is coming from the underlying OS, not from .Net. Even so, the fact that it has a new line at the end is just an inconsistency in how it was written. If you know it exists like that (and other error messages may do so as well), at least you can deal with the case gracefully in your own code by trimming the newline from the end.

adrianbanks
I looked around with reflector and the message is indeed coming from the OS, not the .Net framework, via the GetMessage API.
adrianm
+1  A: 

There are two sources of exception message text. First are string resources in mscorlib.dll, the second is text generated by Windows itself with the FormatMessage() API. The error code for your example is 183, ERROR_ALREADY_EXISTS. Mscorlib.dll does contain a dedicated string resource for that error:

IO.IO_AlreadyExists_Name=Cannot create "{0}" because a file or directory with the same name already exists.

No linefeed in that message. The code that generates the exception message (System.IO.WinIOError) first checks if there's a meaningful file name to generate for the {0} composite formatting argument. Apparently that fails in your program, that's a bit odd. The fallback is the Windows error message produced by FormatMessage() and it's not quite formatted the same way as the resource strings as you found it.

It could be argued that this is a bug, you could report it at connect.microsoft.com. The odds that this will get fixed are zero though. There's some soul out there that is parsing the Message property, especially since this is an IOException. Trimming like you did is a good workaround.

Hans Passant