I have just inherited some code that sends a file from server to client. However, the code only works for text files, and I'm trying to modify it so that it can send and receive zipped files too. But I'm stuck, and don't know how to go about changing it.
The current code looks like this:
- //SERVER
- private void SendFileToClient(SocketPacket state, string PFilename)
- {
- if (File.Exists(PFilename))
- {
- FileStream fileStream = File.Open(PFilename, FileMode.Open, FileAccess.Read, FileShare.Read);
- StreamReader reader = new StreamReader(fileStream);
- byte[] sendBytes = Encoding.ASCII.GetBytes(reader.ReadToEnd());
- MessageBox.Show(sendBytes.Length + "");
- state.m_currentSocket.Send(sendBytes, 0, sendBytes.Length, SocketFlags.None);
- fileStream.Close();
- reader.Close();
- }
- }
- //CLIENT
- public void OnDataReceived(IAsyncResult asyn)
- {
- try
- {
- SocketPacket theSockId = (SocketPacket)asyn.AsyncState;
- int iRx = theSockId.thisSocket.EndReceive(asyn);
- char[] chars = new char[iRx + 1];
- System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
- int charLen = d.GetChars(theSockId.dataBuffer, 0, iRx, chars, 0);
- System.String szData = new System.String(chars);
- theSockId.message += szData;
- if ((theSockId.message.Length > 0) && ((theSockId.message[0] != '<') ||
- ((theSockId.message[0] == '<') && (theSockId.message.IndexOf("") > -1))))
- {
- DealWithResponse(theSockId);
- }
- else
- WaitForData(theSockId);
- }
- catch (ObjectDisposedException)
- {
- System.Diagnostics.Debugger.Log(0, "1", "\nOnDataReceived: Socket has been closed\n");
- }
- catch (SocketException se)
- {
- MessageBox.Show(se.Message);
- }
- }
- public void DealWithResponse(SocketPacket theSockId)
- {
- if (theSockId.message != null)
- {
- FileStream fileStream = File.Open(theSockId.theGame.KeyFile, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None);
- StreamWriter writer = new StreamWriter(fileStream);
- writer.Write(theSockId.message);
- writer.Close();
- fileStream.Close();
- }
- }
Let me know if you need more of the code. Thank you for taking your time to look at this.

Jan MontanoRank #1,295 · 1.3K reputationPosted Jan 26, 2009, 1:21 AM EST
Ska5 reputationPosted Jan 26, 2009, 2:50 PM EST
Can you please point out how I may be able to use that in the above code?
Sorry for being useless.
Jan MontanoRank #1,295 · 1.3K reputationPosted Jan 26, 2009, 4:32 PM EST
long fileLength = fileStream.Length;
byte[] sendBytes = new byte[fileLength];
Ska5 reputationPosted Jan 27, 2009, 12:23 AM EST
Will I still receive it the same way?
Jan MontanoRank #1,295 · 1.3K reputationPosted Jan 28, 2009, 6:46 PM EST
Buzz me if you're having a problem with it.