I cant receive anything other than text files - c#

I have tried every solution I could find but nothing seems to work. Anything other than text files becomes corrupted; someone said that TCP can't send more than 8KB, so I tried to fix the problem and I think I did. Now, when I send a text file (no matter what size it is), it reaches perfectly but anything else gets corrupted. I know the code for the cutting is expensive to performance but I am going to think about that later.
Here is my sender code:
private string SendFile(string tosend, string tosendname)
{
ipadd = IPAddress.Parse(textBox2.Text);
ep = new IPEndPoint(ipadd, 6112);
Sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
Sender.Connect(ep);
Thread.Sleep(100);
byte[] filetosend = System.IO.File.ReadAllBytes(tosend);
FileStream fs = new FileStream(tosend, FileMode.Open, FileAccess.Read);
//Read byte from image
fs.Read(filetosend, 0, filetosend.Length);
fs.Flush();
fs.Close();
int countt = filetosend.Count();
int dividedcount = countt / 7000;
Sender.Send(Encoding.ASCII.GetBytes("filesize#" + filetosend.Count().ToString()));
Thread.Sleep(500);
List<byte> cuttedtosend = new List<byte>();
for (int counti = 0; counti < dividedcount; counti++)
{
cuttedtosend = new List<byte>();
for (int index = 0; index < 7000; index++)
{
cuttedtosend.Add(filetosend[(filetosend.Count() - countt) + index]);
}
Sender.Send(cuttedtosend.ToArray());
Thread.Sleep(100);
countt -= 7000;
richTextBox1.Invoke((MethodInvoker)delegate { richTextBox1.AppendText("Countt = " + countt + "\n"); });
richTextBox1.Invoke((MethodInvoker)delegate { richTextBox1.AppendText("Counti = " + counti + "\n"); });
}
richTextBox1.Invoke((MethodInvoker)delegate { richTextBox1.AppendText("Done"); });
cuttedtosend = new List<byte>();
for (int index = filetosend.Count() - countt; index < filetosend.Count(); index++)
{
//richTextBox1.Invoke((MethodInvoker)delegate { richTextBox1.AppendText(index + "this is 2 \n"); });
cuttedtosend.Add(filetosend[index]);
}
Sender.Send(cuttedtosend.ToArray());
countt -= countt;
return "";
}
And here is my receive code:
private async void StartReceiving()
{
List<byte> neededbytes = new List<byte>();
receivedbyte = new byte[InputForm.s];
Receiver.Bind(new IPEndPoint(IPAddress.Parse("0"), 6112));
Receiver.Listen(1000);
string filename = "Downloadedfile";
bool cont = false;
while (true)
{
Client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
Client = Receiver.Accept();
int filesize = 0;
byte[] receivechecker = new byte[100];
Client.Receive(receivechecker);
if(Encoding.ASCII.GetString(receivechecker).Contains("filesize#"))
{
filesize = Convert.ToInt32(Encoding.ASCII.GetString(receivechecker).Remove(0, 9));
Client.Receive(receivechecker);
}
if (Encoding.ASCII.GetString(receivechecker).Contains("#100254#"))
{
string[] splttedtext = Encoding.ASCII.GetString(receivechecker.ToArray()).Split('#');
if (splttedtext[0] == "mess")
{
MessageBox.Show(splttedtext[2]);
}
else if (splttedtext[0] == "filename")
{
//MessageBox.Show(splttedtext[2]);
filename = splttedtext[2];
//filename.Replace(#"\", #"/");
cont = true;
}
}
else
{
List<byte> tosave = new List<byte>();
richTextBox1.Invoke((MethodInvoker)delegate { richTextBox1.AppendText(filesize.ToString() + "\n"); });
int countt = filesize / 7000;
FileStream writer = File.Create("DownloadedFile.jpg");
for (int counti = 0; counti < countt; counti++)
{
byte[] toadd = new byte[7000];
richTextBox1.Invoke((MethodInvoker)delegate { richTextBox1.AppendText("Counti = " + counti.ToString() + "\n"); });
Client.Receive(toadd);
writer.Write(toadd,0,toadd.Count());
neededbytes.AddRange(toadd);
filesize -= 7000;
}
richTextBox1.Invoke((MethodInvoker)delegate { richTextBox1.AppendText(filesize.ToString() + "\n"); });
byte[] toadds = new byte[filesize];
Client.Receive(toadds);
writer.Write(toadds,0,toadds.Count());
writer.Close();
neededbytes.AddRange(toadds);
filesize -= filesize;
}
}
Thanks in advance :D
Edit:
I just tried Sending a 7mb text file and it reached complete.......

The most immediate problem is that you're saving bytes that you didn't necessarily receive. For example, you have:
for (int counti = 0; counti < countt; counti++)
{
byte[] toadd = new byte[7000];
richTextBox1.Invoke((MethodInvoker)delegate { richTextBox1.AppendText("Counti = " + counti.ToString() + "\n"); });
Client.Receive(toadd);
writer.Write(toadd,0,toadd.Count());
neededbytes.AddRange(toadd);
filesize -= 7000;
}
The documentation for Receive says that the method will receive up to the number of bytes you request. It's not uncommon for it to return fewer bytes than you requested, especially at the end of the file (since it couldn't receive more than the file length).
You need to write:
var bytesRead = Client.Receive(toadd);
writer.Write(toadd, 0, bytesRead); // only write as many bytes as you've read
In general, your code is pretty convoluted, and you have several other possible problems just waiting to bite you. For example, the code that sends the file size sleeps for 500 ms, which just happens to be enough time for the receiver to read just the number of bytes sent. Without that sleep, your code would fail.
You have code to receive the file name, but no code to send it.
I would suggest that you eliminate the ASCII tags and send things in binary. Below is your rewritten Send method.
private string SendFile(string tosend, string tosendname)
{
ipadd = IPAddress.Parse(textBox2.Text);
ep = new IPEndPoint(ipadd, 6112);
Sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
Sender.Connect(ep);
byte[] filetosend = System.IO.File.ReadAllBytes(tosend);
byte[] filesizeBytes = BitConverter.GetBytes(filetosend.Length);
Sender.Send(filesizeBytes); // sends the length as an integer
// note: You could use Socket.Send(filetosend) here.
// but I'll show an example of sending in chunks.
int totalBytesSent = 0;
while (totalBytesSent < filetosend.Length)
{
int bytesLeft = filetosend.Length - totalBytesSent;
int bytesToSend = Math.Min(bytesLeft, 7000);
Sender.Send(filetosend, totalBytesSent, bytesToSend);
richTextBox1.Invoke((MethodInvoker)delegate
{ richTextBox1.Append(totalBytesSent + " bytes sent\n"); });
totalBytesSent += bytesToSend;
}
richTextBox1.Invoke((MethodInvoker)delegate { richTextBox1.AppendText("Done"); });
return "";
}
The receiver code is similarly simplified:
private async void StartReceiving()
{
Receiver.Bind(new IPEndPoint(IPAddress.Parse("0"), 6112));
Receiver.Listen(1000);
string filename = "Downloadedfile";
bool cont = false;
while (true)
{
Client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
Client = Receiver.Accept();
// read the length
byte[] filesizeBytes = new byte[4];
int totalBytesReceived = 0;
while (totalBytesReceived < 4)
{
int bytesRead = Client.Receive(
filesizeBytes, totalBytesReceived, 4-totalBytesReceived);
totalBytesReceived += bytesRead;
}
int filesize = BitConverter.ToInt32(filesizeBytes);
richTextBox1.Invoke((MethodInvoker)delegate
{ richTextBox1.AppendText(filesize.ToString() + "\n"); });
// now read the file
using (FileStream writer = File.Create("DownloadedFile.jpg"))
{
byte[] readBuffer = new byte[7000];
totalBytesReceived = 0;
while (totalBytesReceived < filesize)
{
int bytesToRead = Math.Min(7000, filesize - totalBytesReceived);
int bytesRead = Client.Receive(readBuffer, 0, bytesToRead);
totalBytesRead += bytesRead;
writer.Write(readBuffer, 0, bytesRead);
richTextBox1.Invoke((MethodInvoker)delegate
{ richTextBox1.AppendText("Read " + bytesRead.ToString() + "bytes\n"); });
}
richTextBox1.Invoke((MethodInvoker)delegate
{ richTextBox1.AppendText("Done. " + totalBytesRead.ToString() + " bytes\n"); });
}
}
If you want to send the file name, then I would suggest converting it to UTF8 (Encoding.UTF8.GetBytes(filename)), then send an int (4 bytes) that says how long it is, and then the buffer. To receive it, read the 4-byte filename length like I showed how to read the file size, then that many bytes for the file name, and convert back to a string (Encoding.UTF8.GetString(bytes, 0, filenameLength)).
Please excuse any typos or minor errors in the code. I'm doing this from memory and trying to keep somewhat with your coding style.

i suspect that you are expecting the same blocks that you send to be received; ie that record boundaries will be preserved. This is not so. TCP guarantees that every byte sent will be received and that order is preserved; but you could do 1 large 10k send and receive 10k 1 byte messages.

Related

C# - How can I receive filename and file from my Java app

I am very new to Java and C#. I have a java app that is sending the filename and file to a C# client using TCP Socket. I receive the data but it is corrupt when writing. I do not know how to first read the file name and then rest of the data to write the file.
I have written code that if I just send the file from my java app I successfully receive it on my C# app and write it successfully. This works 100%. Now I want to send the name and file.
Java code sending the data:
try {
System.out.println("Connecting...");
File file = new File(Environment.getExternalStorageDirectory(), backup_folder);
File[] Files = file.listFiles();
OutputStream os = m_socket.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
dos.writeInt(Files.length);
for (int count = 0; count < Files.length; count++) {
dos.writeUTF(Files[count].getName());
}
for (int count = 0; count < Files.length; count++) {
int filesize = (int) Files[count].length();
dos.writeInt(filesize);
}
for (int count = 0; count < Files.length; count++) {
int filesize = (int) Files[count].length();
byte[] buffer = new byte[filesize];
FileInputStream fis = new FileInputStream(Files[count].toString());
BufferedInputStream bis = new BufferedInputStream(fis);
//Sending file name and file size to the server
bis.read(buffer, 0, buffer.length); //This line is important
dos.write(buffer, 0, buffer.length);
dos.flush();
//close socket connection
//socket.close();
}
m_socket.close();
} catch (Exception e) {
System.out.println("Error::" + e);
//System.out.println(e.getMessage());
//e.printStackTrace();
//Log.i("******* :( ", "UnknownHostException");
}
}
C# code (this is where I am having my problem)
private void WaitConnection()
{
toolStripStatusLabel2.Visible = true;
toolStripStatusLabel1.Visible = false;
while (true){
m_listener.Start();
m_client = m_listener.AcceptTcpClient();
if (m_client.Connected == true)
{
this.Invoke((MethodInvoker)delegate
{
this.toolStripStatusLabel4.Visible = false;
this.toolStripStatusLabel5.Visible = false;
this.toolStripStatusLabel3.Visible = true;
});
}
using (var stream = m_client.GetStream())
using (var output = File.Create("C:\\Stocktake\\EDADatabase.db"))
{
byte[] buffer;
buffer = new byte[1024];
int bytesRead = -1;
progressBar1.BeginInvoke(new MethodInvoker(delegate { progressBar1.Maximum = 50; })); //Set Progessbar maximum
while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
{
var xml = Encoding.UTF8.GetString(buffer,0,bytesRead);
string rec = System.Text.Encoding.ASCII.GetString(buffer, 0, bytesRead);
output.Write(buffer, 0, bytesRead);
progressBar1.Invoke(new updatebar(this.UpdateProgress));
}
if (bytesRead == 0)
{
Completed = true;
this.Invoke((MethodInvoker)delegate
{
this.m_client.GetStream().Close();
this.m_client.Dispose();
this.m_listener.Stop();
this.toolStripStatusLabel3.Visible = false;
this.toolStripStatusLabel5.Visible = true;
});
progressBar1.Invoke(new updatebar(this.UpdateProgress));
//break;
}
}
}
}
All I want to do is read the file name and use the file name to read and save the data to my pc.

Transformation an image file in tcp/ip

I convert image file into a byte array and packetize it to 14-byte packets and send it via SerialPortEventHandler. on the other hand, in reciever part I lost some packets and when I generate recieved byte array in a new image file, the rest of the image, after the lost packet, shifted incorrectly, I have replaced lost packets with zero. while this works with text file perfectly. This is my code in client and server side:
client
_file = ofile.ConvertFileToByte(txtFileName.Text);
for (int k = 0; k < Configuration.PacketNumberInFrame; k++)
{
((BackgroundWorker)sender).ReportProgress((j * Configuration.PacketNumberInFrame + i) * 100 / Configuration.FileCount);
if (i + _numberOfByte <= Configuration.FileCount)
_packet = _file.SubArray(i, _numberOfByte);
}
//send packet
...
Server
try
{
while (true)
{
size = port.BytesToRead;
if (size >= 18)
break;
}
byte[] packet = new byte[size];
var str2 = port.Read(packet, 0, size);
if (System.Text.Encoding.Default.GetString(packet).Contains(Configuration.EndKeyByte) && !endFlag)
EndRecieving();
else
Extract(packet);
}
catch
(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public Extract(packet)
{
Recieve_Data.Add( packet);
}
public EndRecieving()
{
for(int i=0;i< arrayResult.AddRange(packetData);i++)
{
arrayResult.AddRange(packetData);
}
string filePath = Configuration.LogFilePath + "\\CreatedFile-" + "."filePrefix.ToLower();
var stream = new FileStream(filePath,
FileMode.Create,
FileAccess.ReadWrite);
FileData oFile = new FileData();
stream.Write(result, 0, result.Length);
stream.Close();
}

send byte[] data over network stream socket. c#

i want to send string json over networkstream . code at client side
using (var ns = new NetworkStream(socket))
{
string json = JsonConvert.SerializeObject(listCfile, Formatting.Indented);
byte[] jsonbytes = Encoding.UTF8.GetBytes(json);
byte[] jsonLength = BitConverter.GetBytes(jsonbytes.Length);
ns.Write(jsonLength, 0, jsonLength.Length);
ns.Write(jsonbytes, 0, jsonbytes.Length);
}
jsonbytes was byte[988324]
At server side
using (var ns = new NetworkStream(socket))
{
byte[] byDataLength = new byte[4];
ns.Read(byDataLength, 0, 4);
int jsonLength = BitConverter.ToInt32(byDataLength, 0);
byte[] byData = new byte[jsonLength];
ns.Read(byData, 0, jsonLength);
File.WriteAllBytes("E:\\json.txt",byData);
}
byData was byte[988324]
But byData i received isn't same as jsonbytes i sent.
i need some helps.
Update! some times it works. ByData received is same as jsonbytes i sent
Some times it doesn't work :(
You can try using raw sockets to send and receive as well as using a memory stream and end-of-packet mechanism for unknown data lengths.
Below is a snippet of methods showing using raw sockets and buffering in a memory-stream till End-Of-Packet is detected.
protected const int SIZE_RECEIVE_BUFFER = 1024; /// Receive buffer size
protected const string EOF = "!#~*|"; /// End of packet string
MemoryStream _msPacket = new MemoryStream(); /// Memory stream holding buffered data packets
int _delmtPtr = 0; /// Ranking pointer to check for EOF
Socket _baseSocket;
public event EventHandler OnReceived;
// TODO: -
// Add methods to connect or accept connections.
// When data is send to receiver, send with the same EOF defined above.
//
//
public void RegisterToReceive()
{
byte[] ReceiveBuffer = new byte[SIZE_RECEIVE_BUFFER];
_baseSocket.BeginReceive
(
ReceiveBuffer,
0,
ReceiveBuffer.Length,
SocketFlags.None,
new AsyncCallback(onReceiveData),
ReceiveBuffer
);
}
private void onReceiveData(IAsyncResult async)
{
try
{
byte[] buffer = (byte[])async.AsyncState;
int bytesCtr = 0;
try
{
if (_baseSocket != null)
bytesCtr = _baseSocket.EndReceive(async);
}
catch { }
if (bytesCtr > 0)
processReceivedData(buffer, bytesCtr);
RegisterToReceive();
}
catch{ }
}
private void processReceivedData(byte[] buffer, int bufferLength)
{
byte[] eof = Encoding.UTF8.GetBytes(EOF);
int packetStart = 0;
for (int i = 0; i < bufferLength; i++)
{
if (buffer[i].Equals(eof[_delmtPtr]))
{
_delmtPtr++;
if (_delmtPtr == eof.Length)
{
var lenToWrite = i - packetStart - (_delmtPtr - 1);
byte[] packet = new byte[lenToWrite + (int)_msPacket.Position];
if (lenToWrite > 0)
_msPacket.Write(buffer, packetStart, lenToWrite);
packetStart = i + 1;
_msPacket.Position = 0;
_msPacket.Read(packet, 0, packet.Length);
try
{
if (OnReceived != null)
OnReceived(packet, EventArgs.Empty);
}
catch { }
_msPacket.Position = 0;
_delmtPtr = 0;
}
}
else
{ _delmtPtr = 0; }
}
if (packetStart < bufferLength)
_msPacket.Write(buffer, packetStart, bufferLength - packetStart);
if (_msPacket.Position == 0)
_msPacket.SetLength(0);
}
This can receive large length of data and is independent of length by the sender.
The methods above shows how to receive data only, so will have to include other methods for connect, accept, sending-data, etc on raw sockets.

How can I make each flush() work, which make each buffer sent before next write() in C#

I am trying to sent very screenshot when i move the mouse on the screen. Therefore, I will sent the size of screenshot and image byte[]. In my client side, I will set the size byte array by the size received from server, and read the rest of byte[] as image. Ideally, I need each time I call the write(), the byte[] I want write into should be empty, so I use the flush(). In fact, after I received the getinputstream(), Sometime I will get the old data inside it. I don't know why flush() doesn't work. anyone has better ideas to solve this problem?
This is my code for server, I try use stream, and networkstream, it dosent works.
public void send(byte[] imageByte)
{
Stream stream = client.GetStream();
client.NoDelay = true;
client.Client.NoDelay = true;
Debug.WriteLine("noDelay:{0}, client.noDelay:{1}", client.NoDelay, client.Client.NoDelay);
byte[] imageSize;
string imgSize = Convert.ToString(imageByte.Length);
Debug.WriteLine("string=" + imgSize);
imageSize = Encoding.ASCII.GetBytes(imgSize);
Debug.WriteLine(" header size:" + imageSize.Length);
//ns.Write(imageSize, 0, imageSize.Length);
//ns.Flush();
//sleep 500 ms
stream.Write(imageSize, 0, imageSize.Length);
stream.Flush();
Thread.Sleep(150);
Debug.WriteLine("sent size");
//ns.Write(imageByte, 0, imageByte.Length);
//ns.Flush();
stream.Write(imageByte, 0, imageByte.Length);
stream.Flush();
Debug.WriteLine("First time sent image size:" + imageByte.Length);
client side:
public class connection extends AsyncTask {
private byte[] data;
public void setByteSize(int size) {
data = new byte[size];
}
public byte[] getByteSize() {
return data;
}
#Override
protected Object doInBackground(Object... arg0) {
try {
clientSocket = new Socket("134.129.125.126", 8080);
// clientSocket = new Socket("134.129.125.172", 8080);
System.out.println("client connect to server");
input = clientSocket.getInputStream();
System.out.println("getinputstream");
} catch (UnknownHostException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
while (true) {
int totalBytesRead = 0;
int chunkSize = 0;
int tempRead = 0;
String msg = null;
// byte[] data = null;
byte[] tempByte = new byte[1024 * 1024 * 4];
try {
// read from the inputstream
tempRead = input.read(tempByte);
// tempbyte has x+5 byte
System.out.println("Fist time read:" + tempRead);
// convert x+5 byte into String
String message = new String(tempByte, 0, tempRead);
msg = message.substring(0, 5);
int msgSize = Integer.parseInt(msg);
data = new byte[msgSize];
// for(int i =0;i<tempRead-5;i++)
// {
// data[i]=tempByte[i+5];
// }
for (int i = 0; i < msgSize; i++) {
data[i] = tempByte[i + 5];
}
// cut the header into imageMsg
// String imageMsg = new String(tempByte, 5, tempRead - 5);
// convert string into byte
System.out.println("message head:" + msg);
byteSize = Integer.parseInt(msg);
System.out.println("ByteSize:" + byteSize);
// convert String into byte[]
totalBytesRead = tempRead - 5;
System.out.println("total Byte Read=" + totalBytesRead);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// get string for the size of image
try {
while (totalBytesRead != getByteSize().length) {
System.out.println("data length:"
+ getByteSize().length);
chunkSize = input.read(getByteSize(), totalBytesRead,
getByteSize().length - totalBytesRead);
System.out.println("chunkSize is " + chunkSize);
totalBytesRead += chunkSize;
// System.out.println("Total byte read "
// + totalBytesRead);
}
System.out.println("Complete reading - total read = "
+ totalBytesRead);
} catch (Exception e) {
}
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
System.out.println("deco");
runOnUiThread(new Runnable() {
public void run() {
image.setImageBitmap(bitmap);
System.out.println("setImage at less than 500");
}
});
}
}
}

C# FileStream reads bytes incorrectly

I am trying to develop an app that will upload large files to a web server running PHP. Almost immediately, I stumbled upon a problem that the file is not split correctly.
Currently I have this piece of code
string adrese = "c:\\directory\\file.jpg";
int garums = 16384;
String ext = Path.GetExtension(adrese);
FileStream file = /*/File.Open(adrese, FileMode.Open);/*/
new FileStream(adrese, FileMode.Open, System.IO.FileAccess.Read);
long fgar = file.Length; //100%
long counter = garums;
first = true;
byte[] chunk = new byte[garums];
while (true)
{
int index = 0;
//long Controll = counter+garums;
while (index < chunk.Length)
{
int bytesRead = file.Read(chunk, index, chunk.Length - index);
if (bytesRead == 0)
{
/*byte[] biti = new byte[index];
for (int i = 0; i < index; i++)
{
biti[i] = chunk[i];
}
chunk = new byte[index];
chunk = biti;*/
break;
}
index += bytesRead;
}
if (index != 0) // Our previous chunk may have been the last one
{
byte[] biti = new byte[index];
for (int i = 0; i < index; i++)
{
biti[i] = chunk[i];
}
chunk = new byte[index];
chunk = biti;
// index is the number of bytes in the chunk
sutam(Convert.ToBase64String(chunk),ext);
}
double procentuali = ((counter * 100) / fgar);
if (procentuali > 99)
{
procentuali = 100;
}
progressBar1.Value = (int)Math.Round(procentuali);
label1.Text = "" + procentuali;
counter = counter+garums;
if (index != garums) // We didn't read a full chunk: we're done
{
return;
}
}
file.Close();
Everything works if I set garums to 1, but who will wait for a year or so to upload a file sized multiple GB's.
I would be pleased if you could tell me what is wrong and how to fix this.
Try this instead to upload in chunks:
private void ConvertToChunks()
{
//Open file
string file = MapPath("~/temp/1.xps");
FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
//Chunk size that will be sent to Server
int chunkSize = 1024;
// Unique file name
string fileName = Guid.NewGuid() + Path.GetExtension(file);
int totalChunks = (int)Math.Ceiling((double)fileStream.Length / chunkSize);
// Loop through the whole stream and send it chunk by chunk;
for (int i = 0; i < totalChunks; i++)
{
int startIndex = i * chunkSize;
int endIndex = (int)(startIndex + chunkSize > fileStream.Length ? fileStream.Length : startIndex + chunkSize);
int length = endIndex - startIndex;
byte[] bytes = new byte[length];
fileStream.Read(bytes, 0, bytes.Length);
ChunkRequest(fileName, bytes);
}
}
private void ChunkRequest(string fileName,byte[] buffer)
{
//Request url, Method=post Length and data.
string requestURL = "http://localhost:63654/hello.ashx";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestURL);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
// Chunk(buffer) is converted to Base64 string that will be convert to Bytes on the handler.
string requestParameters = #"fileName=" + fileName + "&data=" + HttpUtility.UrlEncode( Convert.ToBase64String(buffer) );
// finally whole request will be converted to bytes that will be transferred to HttpHandler
byte[] byteData = Encoding.UTF8.GetBytes(requestParameters);
request.ContentLength = byteData.Length;
Stream writer = request.GetRequestStream();
writer.Write(byteData, 0, byteData.Length);
writer.Close();
// here we will receive the response from HttpHandler
StreamReader stIn = new StreamReader(request.GetResponse().GetResponseStream());
string strResponse = stIn.ReadToEnd();
stIn.Close();
}

Categories