Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save file to ftp server

Tags:

c#

.net

file

upload

I'm creating a file uploader in asp.net and c#. I just wanted to save that uploaded files to ftp server directly. Is it possible? And if it is possible, how can I set that ftp server authentication information.

(127.0.0.1 is just an example. I couldn't write my real ip. And I have to get files using HTTP protocol. Some of our clients ISPs don't support ftp. That's the main problem.)

protected void submit_button_Click(object sender, EventArgs e)
    {
        string filename = Path.GetFileName(upload_file.FileName);
        string fileExt = Path.GetExtension(upload_file.FileName);

        if (fileExt == ".csv")
        {
            string folder = Server.MapPath("ftp://127.0.0.1/uploads/");
                upload_file.SaveAs(folder + "/" + filename);
                ltr.Text = "Successful.";
        }
        else
        {
            upload_file.BorderColor = System.Drawing.Color.Red;
            ltr.Text = "File type must be .csv.";
        }
    }
like image 918
user2163530 Avatar asked Feb 17 '23 16:02

user2163530


1 Answers

Its pretty simple. The below method just pass in the file name. Obviously change the directory in the StreamReader.

EDIT: Sorry just noticed you said your client doesnt support FTP so the below wont work.

public bool ftpTransfer(string fileName)
{
    try
    {
        string ftpAddress = "127.0.0.1";
        string username = "user";
        string password = "pass";

        using (StreamReader stream = new StreamReader("C:\\" + fileName))
        {
            byte[] buffer = Encoding.Default.GetBytes(stream.ReadToEnd());

            WebRequest request = WebRequest.Create("ftp://" + ftpAddress + "/" + "myfolder" + "/" + fileName);
            request.Method = WebRequestMethods.Ftp.UploadFile;
            request.Credentials = new NetworkCredential(username, password);
            Stream reqStream = request.GetRequestStream();
            reqStream.Write(buffer, 0, buffer.Length);
            reqStream.Close();
        }
        return true;
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
        return false;
    }
}

Edit: Reworked the filename.

like image 134
CathalMF Avatar answered Feb 27 '23 18:02

CathalMF