开发者

Problem in Base64 encoding and decoding in C#

开发者 https://www.devze.com 2023-01-18 13:20 出处:网络
I have a problem here in encoding and decoding of a pdf or docx file.Please find the code below. string FileName = @\"C:\\Tips.docx\";

I have a problem here in encoding and decoding of a pdf or docx file.Please find the code below.

string FileName = @"C:\Tips.docx";   
FileStream inFile = new FileStream(FileName, FileMode.Open, FileAccess.Read);
binarydata = new byte[inFile.Length];   
string Base64String = System.Convert.ToBase64String(binarydata,0,binarydata.Length);
byte[] decoded = System.Convert.FromBase64String(Base64String);
StreamWriter writer = new StreamWriter(@"C:\Tips1.docx", f开发者_Go百科alse, System.Text.Encoding.ASCII);
writer.Write(Base64String);
writer.Close();

I am unable to open Tips1.docx file saying File is corrupted.

Can any one tell me whats wrong in the code?


You're not reading the data - you're just creating a byte array of the appropriate length and then converting that array of zeroes into base 64.

Use File.ReadAllBytes to read a file into memory completely in a very simple way... or if you really want to do it by hand, loop round reading the data into the buffer - you shouldn't rely on a single call to Stream.Read to read everything.

If you want to write binary data, use File.WriteAllBytes, and to write text, use File.WriteAllText.

Even when you've managed to write out the base64 data though, you won't be able to open it as in Word - because it's just a text file of base64 text... you either want to write out the decoded binary data, or you want to write the base64 data out to something which will then decode it later. (Currently you're just throwing away the decoded data.)

Finally, not that in times where you do use a StreamWriter, you should use a using statement to make sure it's disposed even if it throws an exception.


You're not reading the data, and you're also writing the Base64 data, not the decoded binary.


If you are intending to actually copy the content, it would be a whole lot easier by using System.IO.File.Copy() method.

0

精彩评论

暂无评论...
验证码 换一张
取 消