jaime-olivares / zipstorer

A Pure C# Class to Store Files in Zip
MIT License
182 stars 63 forks source link

[sharing] Using CP437 in .NET Framework 4.8 #52

Open adriancs2 opened 1 month ago

adriancs2 commented 1 month ago

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 commented 1 month ago

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" :)

jaime-olivares commented 2 weeks ago

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 commented 1 week ago

hi @adriancs2

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