Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transferring to ftp site using HttpWebRequest

I'm trying to transfer an Excel file to an sftp site and my code executes properly, but I do not see the file on the site.

private static void SendFile(string FileName)
{
    FileStream rdr = new FileStream(FileName + ".csv", FileMode.Open);
    HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://sftp.somesite.com");
    HttpWebResponse resp;
    req.Method = "Post";
    req.Credentials = new NetworkCredential("UN", "PW", "Domain");

    req.ContentLength = rdr.Length;
    req.AllowWriteStreamBuffering = true;
    Stream reqStream = req.GetRequestStream();
    byte[] inData = new byte[rdr.Length];
    int bytesRead = rdr.Read(inData, 0, Convert.ToInt32(rdr.Length));

    reqStream.Write(inData, 0, Convert.ToInt32(rdr.Length));
    rdr.Close();
}

What am I doing wrong in the code above?

like image 621
Eric Avatar asked Mar 05 '26 10:03

Eric


1 Answers

Why don't you use FtpWebRequest instead?

using System.Net;
using System.IO;

public class Ftp
{
  private static void ftpUpload(string filename, string destinationURI)
  {
        FileInfo fileInfo = new FileInfo(filename);
        FtpWebRequest reqFTP = CreateFtpRequest(new Uri(destinationURI));

        reqFTP.KeepAlive = false;

        // Specify the command to be executed.
        reqFTP.Method = WebRequestMethods.Ftp.UploadFile;

        // use binary 
        reqFTP.UseBinary = true;

        reqFTP.ContentLength = fileInfo.Length;

        // Buffer size set to 2kb
        const int buffLength = 2048;
        byte[] buff = new byte[buffLength];

        // Stream to which the file to be upload is written
        Stream strm = reqFTP.GetRequestStream();

        FileStream fs = fileInfo.OpenRead();

        // Read from the file stream 2kb at a time
        int cLen = fs.Read(buff, 0, buffLength);

        // Do a while till the stream ends
        while (cLen != 0)
        {
            // FTP Upload Stream
            strm.Write(buff, 0, cLen);
            cLen = fs.Read(buff, 0, buffLength);
        }

        // Close 
        strm.Close();
        fs.Close();
   }
 }
like image 165
edocetirwi Avatar answered Mar 07 '26 00:03

edocetirwi