Maurizio

Maurizio

  • NA
  • 11
  • 1.9k

Getting data from host, convert to string and then to bytes

Jun 12 2011 11:42 AM
Hi.
I want to make a program to download files from a remote host.
So what i do is to send throw sockets all the binary information + a string used as end "mystyring".
To check if i have to continue writing the buffer to the file i first convert all to string, so if i find "mystring" it will finish, if not, i reconvert all to bytes and i copy data.
The problem im having is that, .txt files are writed well, but binaris not, it always show error at opening. I ve tried copying a pdf, and when i open it show all the pages, but in blank :S. Also if i check the size of the original file is always some bytes bigger than the copy.

[CODE]FileStream fs = new FileStream("C:\\Users\\Mauri\\Desktop\\" + item.Name, FileMode.Append, FileAccess.Write);
            BinaryWriter writer = new BinaryWriter(fs);
            bool continua = true;
            while (continua)
            {
                recibido = getSocket(numsock).socketRecv(); // This return the data converted to string.
                words = recibido.Split('|'); //We split "|mystring" to find the end of file.
                foreach (string s in words)
                {
                    if ((String.Compare(s, "mystring") != 0))                        
                        writer.Write(StringToBytes(s)); // Write converted data. 
                    else
                        continua = false; // if we find "mystring", end the action.
                }   
            }
            writer.Close();
            fs.Close();

// Convert string to bytes
public byte[] StringToBytes(String cadena)
        {
            System.Text.ASCIIEncoding codificador = new System.Text.ASCIIEncoding();
            return codificador.GetBytes(cadena);
        }
[/CODE]


The strange thing is that .txt files are writed correctly.
Thanks


Answers (10)