user3802347
user3802347

Reputation: 108

Retrieving Content From WebClient.Download

I am uploading content to a website using Webclient.UploadData.

data ="GetCourses('all')"; //this will return all the courses in the course table.

WebClient wb= new WebClient();
try
{
   byte[] bytes = System.Text.Encoding.UTF8.GetBytes(data);
   byte[] results = wb.UploadData(url, "POST", bytes);
   var returnResult = System.Text.Encoding.ASCII.GetString(results);
} 
catch (Exception ex)
{
   ex.ToString()
}

I am trying the get the data that was sent above on the other side. I am expected to see "GetCourses('all')", but it shows null ("")instead.

var requestData = Request.InputStream;
int length = Convert.ToInt32(requestData.Length);
byte[] strArr = new byte[length];

var strRead = requestData.Read(strArr, 0, length);
string content = string.Empty;

for (int i = 0; i < length; i++)
{
   content = content + strArr[i].ToString();
}

What am I doing wrong here?

Upvotes: 1

Views: 56

Answers (2)

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149656

Use Stream.CopyTo:

var requestData = Request.InputStream;
string str;

using (var ms = new MemoryStream())
{
   requestData.CopyTo(ms);
   str = Encoding.UTF8.GetString(ms.ToArray);
}

Or as smarter people suggested, you can use a StreamReader.ReadToEnd:

var streamReader = new StreamReader(Request.InputStream);
var outputString = streamReader.ReadToEnd();

Upvotes: 1

Richard
Richard

Reputation: 109210

Firstly in:

int length = Convert.ToInt32(requestData.Length)

I think you'll find that requestData.Length is already an int: converting it will just make the code confusing.

But your real problem is in decoding your byte stream. byte.ToString() will treat the byte value as a number, not as a character.

Use

content = Encoding.UTF8.GetString(strArray)

to decode the UTF-8 data into a .NET string. (Note, if the content is long there are ways of doing this incrementally, but for short content that's not worth the effort.)

Also note L.B's comment to the Q: you can also use a StreamReader (but I would be explicit about the encoding.)

Upvotes: 1

Related Questions