Search code examples
c#imap

ERROR: Convert and Save Base64 String into a File


*Edited

Pardon me as I may not have been clear on this one. The code throwing the error is:

Convert.FromBase64String(base64)

Is there another way to convert the base64 string into bytes in C# other than the method above?


I need help with file conversions using C#. I am trying to convert a base64 string into a file and save it into my desktop. The file to be saved is either a text, excel or pdf file. The code I used was this:

File.WriteAllBytes(@"C:\Users\User\Desktop\{thefilename}", Convert.FromBase64String(base64));

However, I am getting an error:

The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters

I tried to save the base64 into a text file first then used https://www.freeformatter.com/base64-encoder.html to convert it to check if the base64 was really in the correct format. When I did that, it converted the base64 into its original file.

May I ask how I am able to resolve this error? Is this error caused by limitations from C# or is it because of the base64 that I had? I don't think it's the latter since I was able to convert it online into its actual file. Is there perhaps any other way to convert a base64 into a file in C# apart from the method I used above?


Solution

  • I may have found the answer to my error. I was able to resolve the error by opening the text file that I saved my base64 string into and then updating it by removing the padding and re-adding it again. The steps went like this:

    1. Save base64 string into text file
    2. Open text file
    3. Remove padding
    4. Save file.
    5. Re-add removed padding
    6. Save file.
    7. Get base64 string from twice-updated text file
    8. Call method Convert.FromBase64String(base64String);

    I'm not sure what caused this issue in the first place. Does anyone know why this is happening? Or is this a Windows OS issue, C# issue or both?