zipstorer icon indicating copy to clipboard operation
zipstorer copied to clipboard

[sharing] Using CP437 in .NET Framework 4.8

Open adriancs2 opened this issue 1 year ago • 3 comments

Here is the latest code of Zipstorer:

static ZipStorer()
{
	// Generate CRC32 table
	CrcTable = new UInt32[256];
	for (int i = 0; i < CrcTable.Length; i++)
	{
		UInt32 c = (UInt32)i;
		for (int j = 0; j < 8; j++)
		{
			if ((c & 1) != 0)
				c = 3988292384 ^ (c >> 1);
			else
				c >>= 1;
		}
		CrcTable[i] = c;
	}

	// Configure CP 437 encoding
	CodePagesEncodingProvider.Instance.GetEncoding(437);
	Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
	DefaultEncoding = Encoding.GetEncoding(437);            
}

In .NET Framework 4.8, you will see this error:

The name 'CodePagesEncodingProvider' does not exist in the current context

This is because CodePagesEncodingProvider is not available in .NET Framework 4.8 by default.

To fix this issue for .NET Framework 4.8, There are couple of options:

Option 1: Use the built-in Encoding.GetEncoding method, which should work for codepage 437 in .NET Framework 4.8 without additional packages.

Option 2: If you need CodePagesEncodingProvider for other reasons in .NET Framework 4.8, you can add the System.Text.Encoding.CodePages NuGet package to your project.

For doing the option 1: Here's the example of using built-in Encoding.GetEncoding

static ZipStorer()
{
    // Generate CRC32 table
    CrcTable = new UInt32[256];
    for (int i = 0; i < CrcTable.Length; i++)
    {
        UInt32 c = (UInt32)i;
        for (int j = 0; j < 8; j++)
        {
            if ((c & 1) != 0)
                c = 3988292384 ^ (c >> 1);
            else
                c >>= 1;
        }
        CrcTable[i] = c;
    }

    // Use the built-in Encoding.GetEncoding method for CP 437
    try
    {
        DefaultEncoding = Encoding.GetEncoding(437);
    }
    catch (NotSupportedException)
    {
        // Fallback to a default encoding if 437 is not supported
        DefaultEncoding = Encoding.Default;
    }
}

adriancs2 avatar Jul 23 '24 00:07 adriancs2

Note: I'm not sure how is this works under the hood, the fix that I've shared above is a code fix suggested by Claude, so that my project can continue to compile without error. And yupe I'm not sure that's the correct fix or not xD since my project compiled without error, I just assumed that the fix is "doing it's job" :)

adriancs2 avatar Jul 23 '24 01:07 adriancs2

I have tried myself the last source code, by adding Net Framework 4.8 to the project. Unit tests are not failing. I have prepared a new beta version in nuget 4.0.2-beta1 so you can try.

jaime-olivares avatar Aug 20 '24 01:08 jaime-olivares

hi @adriancs2

Will you be able to re-test this? Otherwise, I will close this issue as resolved.

jaime-olivares avatar Aug 27 '24 00:08 jaime-olivares