0

Let's say i have a .xlsx file, with password protection, i want to convert this to a string format, and then later when be able to reconstruct the string back to the original .xlsx file keeping all properties (such as the password protection...)

I Tried changing the extension from .xlsx to a .txt, transferring the string content of the .txt and then changing the .txt back to .xlsx... but the file would be corrupted... any ideas?

I Hope my question is clear enough!

Thank you

2 Answers 2

1

i want to convert this to a string format

Firstly, I'd encourage you not to do this unless you really need to. The more conversions you do, the more room there is for error.

However, it's not terribly difficult to do if you really need to - what you're looking for is base64 encoding which can take arbitrary binary data and encoding it into ASCII text - then you can decode the text back to the binary data.

Here's sample C# code to do it:

public static void Base64EncodeFile(string inputFile, string outputFile)
{
    byte[] data = File.ReadAllBytes(inputFile);
    string text = Convert.ToBase64String(data);
    File.WriteAllText(outputFile, text);
}

public static void Base64DecodeFile(string inputFile, string outputFile)
{
    string text = File.ReadAllText(inputFile);
    byte[] data = Convert.FromBase64String(text);
    File.WriteAllBytes(outputFile, data);
}
1

Encode the file to base64 format. Than Decode it to whatever it was before.

5
  • 2
    I agree that base64 is the way to go, but it's important to note that this isn't encryption - it's not like this actually "hides" the data at all.
    – Jon Skeet
    Aug 29, 2020 at 12:43
  • I'm not looking for encrypting or protecting any of the data actually, just a way to transfer a string version of a file format (ex .xlsx) then reconstructing it with all the content/properties intact. Aug 29, 2020 at 12:44
  • @AliAlnuaimi this is not for security reason. This is just for converting everything to string and than recover the file from that.
    – Afshin
    Aug 29, 2020 at 12:46
  • 1
    @AliAlnuaimi: I understand that. I just want to make it clear to anyone reading the answer that base64 encoding it not a form of encryption.
    – Jon Skeet
    Aug 29, 2020 at 12:47
  • @JonSkeet I replaced encrypt with encode. thanks for your hint.
    – Afshin
    Aug 29, 2020 at 12:48

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.