Writing binary data to ftp location

339 views Asked by At

How come this code writes an empty file at given location? No error messages.

// upload file
WebRequest upload = WebRequest.Create(ftp + path + "/" + file);
upload.Method = WebRequestMethods.Ftp.UploadFile;
upload.Credentials = new NetworkCredential(username, password);

String filePath = HttpContext.Current.Server.MapPath("~/temp/" + file); // path to file to upload

Stream myReadStream = new FileStream(filePath, FileMode.Create); // stream that can read binary data

BinaryWriter myStreamWriter = new BinaryWriter(upload.GetRequestStream()); // writer that can write the binary data to the FTP server

while (myReadStream.ReadByte() != -1)
{
    myStreamWriter.Write(myReadStream.ReadByte());
}

myStreamWriter.Close();
myReadStream.Close();

Removing the while loop creates a file 4byte big and corrupt so I guess I cant get in the while loop like this.

1

There are 1 answers

0
Yong Tiger On BEST ANSWER

You should call upload.GetResponse() after myStreamWriter closed.

PS: In the while you write ONE time for every TWO times read, is it really you want?