tags:

views:

85

answers:

3

Hi, 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", false, 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?

+3  A: 

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.

Jon Skeet
Thanks dude.... its working now..........
Pradeep
A: 

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

Andrew Cooper
A: 

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

Amry