将二进制数据写入ftp位置

时间:2013-12-07 15:09:40

标签: c# asp.net stream filestream binarywriter

为什么这段代码会在给定位置写入空文件? 没有错误消息。

// 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();

删除while循环会创建一个4byte大且损坏的文件,所以我想我不能像这样进入while循环。

1 个答案:

答案 0 :(得分:0)

myStreamWriter关闭后,您应该调用upload.GetResponse()

PS:当你每读两次读一次时,你真的想要吗?