-
June 12th, 2011, 06:07 PM
#1
Getting data from host, convert to string and then to bytes again.
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 . 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);
}
The strange thing is that .txt files are writed correctly.
I can't use webclient class, beacuse im not downloading the data from an http or ftp server, is for a connection between 2 computers, like a remote access program.
Thanks
-
June 14th, 2011, 10:42 PM
#2
Re: Getting data from host, convert to string and then to bytes again.
i wrote code to download a file from ftp and it worked
Code:
string filename_remote = "ftp://......................./file.txt";
// read file
WebClient request = new WebClient();
request.Credentials = new NetworkCredential("username", "password0");
byte[] buffer = request.DownloadData(filename_remote);
// get local path
string dir="C:\\TempDataBase";
if (!Directory.Exists(dir)) Directory.CreateDirectory(dir);
string filename_local = Path.GetFileName(filename_remote);
filename_local = dir + "\\" + filename_local;
//write to local
FileStream fs = new FileStream(filename_local, FileMode.Create);
fs.Write(buffer, 0, buffer.Length);
I hope it helps..
(ofcoure you should use your own path, username and password)
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|