Search code examples
c#.neterror-handlingresource-files

What is the best way to associate error messages with error codes in C#?


I have a piece of software written in C#.NET that communicates with a device via USB. When a problem occurs the device sets an error code which is read by my software in the form of an integer. I want to store error messages in my C# program that correlate with the specific firmware error codes. What is the best way to store these?

I have been told that a good approach would be to use a Resource file. What are the benefits of using a resource file? Is there a better way to do it?


Solution

  • I would suggest using a Resource File as well. One key benefit is localization (using different languages). Even if you don't want to use multiple languages today, you give yourself the flexibility to add them later. Another benefit is the simple .NET/c# integration.

    var key = "134"; //error code
    var resourceFile = "someFileName.resx";
    var filePath = @"c:\some\path";
    ResourceManager resourceManager = ResourceManager
        .CreateFileBasedResourceManager(resourceFile, filePath, null);
    resourceValue = resourceManager.GetString(key);
    

    Also, resource files are easy to get to when it comes time to change a message.