user2163530
user2163530

Reputation: 105

Save file to ftp server

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.";
        }
    }

Upvotes: 4

Views: 15773

Answers (2)

chitranjna
chitranjna

Reputation: 131

string filepath = "~/txtfile/";//this is folder name wher you want to save the file


                HttpFileCollection uploadedFiles = HttpContext.Current.Request.Files;
                for (int i = 0; i < uploadedFiles.Count; i++)
                {
                    HttpPostedFile userPostedFile = uploadedFiles[i];
                    if (userPostedFile.ContentLength == 0)
                    {
                        continue;

}



    userPostedFile.SaveAs(Server.MapPath(filepath) + userPostedFile.filename);
} //save file on the server             

Upvotes: 0

CathalMF
CathalMF

Reputation: 10055

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.

Upvotes: 8

Related Questions