Tuesday, April 8, 2014

Upload on FTP Server Using C#

FtpWebRequest fwr = (FtpWebRequest)FtpWebRequest.Create(URI);
// Provide the User Name and Password
fwr.Credentials = new NetworkCredential(USERNAME, PASSWORD);
fwr.KeepAlive = true;
// Specify the transfer type
fwr.UseBinary = true;                       

// Specify the command to be executed.
fwr.Method = WebRequestMethods.Ftp.UploadFile;
// Notify the server about the size of the uploaded file
fwr.ContentLength = uploadfile.ContentLength;

// The buffer size is set to 2kb
int buffLength = Convert.ToInt32(2000);
byte[] buff = new byte[buffLength];
int contentLen;
// Opens a file stream (System.IO.FileStream) to read the file to be uploaded

byte[] bytes = Bytes;
System.IO.Stream stream = new System.IO.MemoryStream(bytes);
Stream fs = stream;
//FileStream fs = (FileStream)fileUpload.PostedFile.InputStream;//fileInf.OpenRead();
// Stream to which the file to be upload is written
Stream strm = fwr.GetRequestStream();

// Read from the file stream 2kb at a time
contentLen = fs.Read(buff, 0, buffLength);
// Till Stream content ends               

while (contentLen != 0)
{
// Write Content from the file stream to the
// FTP Upload Stream
strm.Write(buff, 0, contentLen);
//strm.BeginWrite(buff, 0, contentLen, callBack, buff);
contentLen = fs.Read(buff, 0, buffLength);
}

// Close the file stream and the Request Stream
strm.Close();
fs.Close();

No comments:

Post a Comment