Click here to Skip to main content
15,896,207 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
I have a code to upload the pdf document.While running the code it gives error-
\System.FormatException: Invalid length for a Base-64 char array or string.

My code:
C#
byte[] bDoccontent = null;
HttpWebRequest hwrProg = (HttpWebRequest)WebRequest.Create(URL);
HttpWebResponse hwrpProg = (HttpWebResponse)hwrProg.GetResponse();
StreamReader sr = new StreamReader(hwrpProg.GetResponseStream(), Encoding.ASCII);
bDoccontent = Convert.FromBase64String(sr.ReadToEnd());
sr.Close();
Response.Clear();
Response.ContentType = "Application/pdf";
Page.Response.AddHeader("Content-Disposition", "inline;filename=wei.pdf");
Response.AddHeader("content-length", bDoccontent.Length.ToString());
Response.BinaryWrite(bDoccontent);
Response.Flush();
Response.Close();

Please help me :(
Posted
Updated 1-Sep-14 0:45am
v2

The error means that the string returned by ReadToEnd method is not a Base64 string...
http://msdn.microsoft.com/en-us/library/system.convert.frombase64string(v=vs.110).aspx[^]
 
Share this answer
 
You need to look at exactly what the web request is returning: it isn't just a Base64 string, there is presumably some packaging around it.
Use the debugger, or log the raw data to a file and examine it: there is stuff I think you need to remove - but we can't do that for you as we have no access to your code or the URL...
 
Share this answer
 
You should read an array of chars from the stream and then to finalize your stream reader before to do the conversion.
C#
byte[] bDoccontent = null;
HttpWebRequest hwrProg = (HttpWebRequest)WebRequest.Create(URL);
HttpWebResponse hwrpProg = (HttpWebResponse)hwrProg.GetResponse();
StreamReader sr = new StreamReader(hwrpProg.GetResponseStream(), Encoding.ASCII);
char[] base64CharArray = new char[sr.BaseStream.Length];//New
sr.Read(base64CharArray, 0, (int)sr.BaseStream.Length); //New
sr.Close(); //New
string base64String = new string(base64CharArray); //New
bDoccontent = Convert.FromBase64String(base64String );//New
Response.Clear();
Response.ContentType = "Application/pdf";
Page.Response.AddHeader("Content-Disposition", "inline;filename=wei.pdf");
Response.AddHeader("content-length", bDoccontent.Length.ToString());
Response.BinaryWrite(bDoccontent);
Response.Flush();
Response.Close();
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900