Skip to main content

How to upload file to FTP server using C# Asp.Net #RathrolaPremKumar

This post is about uploading files to FTP server in asp.net development. You will learn step-by-step to upload files programmatically to FTP web server. All the examples shared in this post are intended by professionals to make you learn about the subject
Here, I will explain you an example of Uploading Files to FTP Server programmatically in C#.Net. Using this approach, the Files will be pro grammatically uploaded to FTP Web Server.
For example, I will create a function in which we will simply provide the local file name to upload, upload path of FTP (including host name, FTP username and FTP password). This function uses System.Net and System.IO namespaces to upload the file.

Let’s create a simple console Application to give you example of Uploading Files to FTP Server. So, a new console application will be something like this,


Now, add references of the System.Configuration Assembly to the project in the following way.
1.      Right click on the project and click Add Reference option from the References.

2. From the Add Reference dialog box, click on .Net Tab and look for System.Configuration assembly. Once you find it simply select and click OK. The screen will be displayed something like this.

We can achieve the file uploading task by using the below three inbuilt classes of .NET: FtpWebRequest, WebRequestMethods and NetworkCredential.
First you will need two namespaces to work with FTP. Those are,
using System.Net;
using System.IO;
Then we need to declare five variables as below in App.config file to make it editable any time for different FTPs. So the App.config will look something like this.
<configuration>
<appSettings>
<!--FTP Server URL.-->
<add key="FTPUrl" value="ftp://servername.com/"/>
<!--FTP UserName.-->
<add key="FTPUserName" value="Test"/>
<!--FTP PassWord.-->
<add key="FTPPassWord" value="Test123"/>
<!--FTP FodlerName.-->
<add key="FTPFolderName" value="Uploads/"/>
<!--Local FodlerPath.-->
<add key="LocalFodlerpath" value="D:\LocalFolder\Test.Zip"/>
</appSettings>
</configuration>
Note: Please replace test values of above app.config with your actual values.

Now, Copy the below code and paste in program.cs page (See screen sort below)
Public static void UploadFtpFile(string strfilename)
{
//FTP Server URL.
string ftp = System.Configuration.ConfigurationManager.AppSettings["FTPUrl"];
//FTP Folder name. Leave blank if you want to upload to root folder.
string ftpFolder = System.Configuration.ConfigurationManager.AppSettings["FTPFolderName"];
byte[] fileBytes = null;

//Read the FileName and convert it to Byte array.
string fileName = Path.GetFileName(strfilename);
using (StreamReader fileStream = newStreamReader(strfilename))
            {
                fileBytes = Encoding.UTF8.GetBytes(fileStream.ReadToEnd());
                fileStream.Close();
            }

try
            {
//Create FTP Request.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftp + ftpFolder + fileName);
                request.Method = WebRequestMethods.Ftp.UploadFile;

                request.Timeout = 3000000;
//Enter FTP Server credentials.
                request.Credentials = newNetworkCredential(System.Configuration.ConfigurationManager.AppSettings["FTPUserName"], System.Configuration.ConfigurationManager.AppSettings["FTPPassWord"]);
                request.ContentLength = fileBytes.Length;
                request.UsePassive = true;
                request.UseBinary = true;
                request.ServicePoint.ConnectionLimit = fileBytes.Length;
                request.EnableSsl = false;

using (Stream requestStream = request.GetRequestStream())
                {
                    requestStream.Write(fileBytes, 0, fileBytes.Length);
                    requestStream.Close();
                }

FtpWebResponse response = (FtpWebResponse)request.GetResponse();
                response.Close();
            }
catch (WebException ex)
            {
thrownewException((ex.Response asFtpWebResponse).StatusDescription);
            }
}

Now we will call the above method from Main () function of prgram.cs by passing the local machine file path of from app.config. It is not necessary to pass the local file path from app.config only. You can use the path from variables, sessions or controls as well. Calling the function UploadFTPFile like this, "UploadFtpFile(System.Configuration.ConfigurationManager.AppSettings["LocalFodlerpath"]) " will call the function I wrote when program runs.
Now let's look at the local file path (D:\LocalFolder\Test.zip), show something like this.
Now, you can run application and inside Visual studio you can debug through the process to make sure it works fine.
After completing process. The test.zip file will upload on FTP server you specified and it will look something like this image.
hat's all!! Your zip file has been uploaded to the FTP you specified easily. You might see that I uploaded a file with 30MB size within 2-4 minutes. You can use this function with your existing code where you require to upload file.
Hope this save your time to search about how to upload file on FTP using C#.
Hope this article will help you in uploading files to FTP server in asp.net using C# programming language.

Happy Coding :) 

Comments

  1. I admire the valuable information you offer in your articles. I will bookmark your blog and have my friends check up here often. I am quite sure they will learn lots of new stuff here than anybody else! Regards aws openings in hyderabad.

    ReplyDelete

Post a Comment

Popular posts from this blog

ERROR: Cannot resolve the collation conflict between SQL_Latin1_General_CP1_CI_AS and Latin1_General_CI_AS_KS_WS in the equal to operation

ERROR: Cannot resolve the collation conflict between SQL_Latin1_General_CP1_CI_AS and Latin1_General_CI_AS_KS_WS in the equal to operation
dont get panic if u get the following error while in your joinings, there is a simple way to solve this.
it is because of collation settings on two columns we are doing joinings. it is because of collation settings on two columns we are doing joinings
First step is to figure out what are two colaltion that cause for conflicts. Let us assume that collation has not been set at the column level and instead at db level, then we have to execute two simple statements as below.

Statements: Select DATABASEPROPERTYYEX('DB1',N'Collation') Select DATABASEPROPERTYYEX('DB2',N'Collation')
One more thing, make a note that if you are on sharepoint you will get error as below
Latin_General_CI_AS_KS_WS. if you are on most any other database and use the dafault settings you may get this SQL_Latin_General_CP1_CI_AS.
Now we have to do some…

How To Create The Data Adapter Object Using ADO.NET by #RathrolaPremKumar

By reading this article, you will learn key points in ADO.NET, as given below. What is Data Adapter?Primary Data Adapters for the databases.Data Adapter properties.Methods used by Data Adapter.How to create Data Adapter with an example? Let’s start our demo with a Data Adapter introduction. Actually, we use Data Adapter object to establish the connection to the data source and manage the movement of date to and from the database. What is Data Adapter? A data adapter aobject serves as a bridge between a data set object and Data Source such as a database to retrieve and save the data. Data adapter contains a set of database commands and a database connection, which we use to fill a dataset object and update the Data Source. Primary data adapters for databases? .NET makes two primary data adapters available for use with the databases. Other data adapters can also be integrated with Visual Studio .NET. Primary Data Adapters are mentioned below. OleDbData Adapter, which is suitable for use wi…

'#Resolve' To export a list, you must have a Microsoft SharePoint Foundation-compatible application.

Searching this error message easily finds the root of the problem. There is a problem with the Office 64 bit version. It doesn’t work with SharePoint. These solutions generally tell you to uninstall your 64 bit office and install a 32 bit version. Happily there is a much easier solution.
Despite the error message the export actually works! Notice the yellow bar at the bottom of your browser. Simply save the .iqy file normally and open it with Excel. It’s that simple. The error message is certainly a nuisance but does not actually stop the export.
Thanks for ready my blog :)