0

I have string of text that needs to be cnoverted to base64 before being posted to a url. Here is my code

  HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);
      byte[] postDataBytes = Encoding.UTF8.GetBytes(strCXML);
       string returnValue = System.Convert.ToBase64String(postDataBytes);
       req.Method = "POST";
       req.ContentLength = postDataBytes.Length;
       req.ContentLength = postDataBytes.Length;
       Stream requestStream = req.GetRequestStream();
       requestStream.Write(returnValue,0, postDataBytes.Length);

Problem is i get error on the last line System.IO.Stream.Write(byte[],int,int) returnValue is base64 string cant be used as byte[] needed in stream.writer Any idea how to take that that base64 string called returnvalue and put it to a url thanks

user1108282
  • 55
  • 4
  • 10
  • You need to convert the string to a byte[]. This post shows how http://stackoverflow.com/questions/472906/net-string-to-byte-array-c-sharp – Scott Baldwin Oct 09 '12 at 23:11

2 Answers2

4

You should convert your base64 string into byte array by Encoding.GetBytes

HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);
byte[] postDataBytes = Encoding.UTF8.GetBytes(strCXML);
string returnValue = System.Convert.ToBase64String(postDataBytes);

postDataBytes = Encoding.UTF8.GetBytes(returnValue);

req.Method = "POST";
req.ContentLength = postDataBytes.Length;
Stream requestStream = req.GetRequestStream();
requestStream.Write(postDataBytes, 0, postDataBytes.Length);
SimpleVar
  • 12,897
  • 2
  • 35
  • 58
Viacheslav Smityukh
  • 5,132
  • 2
  • 20
  • 36
0

You are using a Stream as your requestStream. Stream.Write takes a byte array, not a Base64 string.

I think you are doing it in the wrong order. I would convert strCXML to a Base64 String first then encode it into a byte array to write to the request stream.

Gherkin
  • 34
  • 4