Upload file to ftp with unique name in asp.net c#

1.3k Views Asked by At

I wrote below function to upload file to ftp.it's working properly but i need to get uploaded file name.I think ftp server should write file name in response,am i right?

   public static string UploadFileToFTP(string source,string destination)
{
    string filename = Path.GetFileName(source);
    string ftpfullpath = @ConfigurationManager.AppSettings["ftp_url"].ToString();
    FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpfullpath+@destination);
    ftp.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["ftp_user"].ToString(), ConfigurationManager.AppSettings["ftp_pass"].ToString());
    string[] jj = ftp.Headers.GetValues(0);
    ftp.KeepAlive = true;
    ftp.UseBinary = true;
    ftp.Method = WebRequestMethods.Ftp.UploadFileWithUniqueName;

    FileStream fs = File.OpenRead(@source);
    byte[] buffer = new byte[fs.Length];
    fs.Read(buffer, 0, buffer.Length);
    fs.Close();

    Stream ftpstream = ftp.GetRequestStream();
    ftpstream.Write(buffer, 0, buffer.Length);

    ftpstream.Close();
    FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();

    return ConfigurationManager.AppSettings["ftp_http_url"].ToString() + @destination + "/" + response.ToString();//response.?
}
2

There are 2 best solutions below

2
On

You just need to read the Response stream

string fileName = new StreamReader(response.GetResponseStream()).ReadToEnd();

Or better

string fileName;
using(s = new StreamReader(response.GetResponseStream())) {
    fileName = s.ReadToEnd();
}
6
On

I'm not sure why you're going all "bare" and using FtpWebRequest, this can be resolved with three LOC using WebClient, which returns a byte[] response:

using (WebClient webClient = new WebClient())
{
    webClient.Credentials = new NetworkCredential(
                                ConfigurationManager.AppSettings["ftp_user"].ToString(),
                                ConfigurationManager.AppSettings["ftp_pass"].ToString());

    byte[] response = webClient.UploadFile("ftp://address.toserver.com",
                                           WebRequestMethods.Ftp.UploadFileWithUniqueName, 
                                           "PathToLocalFile");
    var fileName = Encoding.UTF8.GetString(response);
}