Solved

how to copy a file from a local machine folder to an FTP folder

Posted on 2013-11-27
6
612 Views
Last Modified: 2013-11-27
I need to copy a text file from a local folder to an ftp folder.

I believe that the steps are:

Read the local file contents into a filestream.

Initiate an FTPWebRequest.

Use a  FTPWebRequest method to copy the filestream to the ftp folder.

Here are my source statements:

   strSourcePath = "C:\\Develop\\Apps\\StockPro\\Data\\Changes\\";
   string strSourceFileName = "Changes.txt";
   string strSourceFile = strSourcePath + strSourceFileName;

// Create a filestream object

     FileStream fs = new FileStream(strSourceFile, FileMode.Open, FileAccess.Read);
     StreamReader sr = new StreamReader(fs);

// Copy the contents of the file to the request stream.
            StreamReader sourceStream = new StreamReader("Changes.txt");
            byte [] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());

// only one column is copied to the request stream.

//Use a  FTPWebRequest method to copy the filestream to the ftp folder.
0
Comment
Question by:Dovberman
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 3
6 Comments
 
LVL 18

Expert Comment

by:Jerry Miller
ID: 39681380
Here is a function that I use to upload files to a FTP server:

Public Shared Function UploadToFTP(ByVal fstream As Stream, ByVal fileName As String, ByVal folder As String) As Boolean
        Dim reqStream As Stream
        Dim ftpWebResponse As FtpWebResponse
        Dim nc As New System.Net.NetworkCredential(ID, Password)
        Dim cc As New System.Net.CredentialCache()
        Dim strFTPFilePath As String
        Dim n_month_name As String = DateTime.Now.ToString("MMMM")
        Dim n_month_num As String = DatePart("m", DateTime.Now).ToString()
        Dim n_year As String = DatePart("yyyy", DateTime.Now).ToString()
        Dim monthFolder As String
        Dim builder As New StringBuilder

        If Len(n_month_num) = 1 Then
            builder.Append("0")
        End If
        builder.Append(n_month_num)
        builder.Append("_")
        builder.Append(n_month_name)
        monthFolder = builder.ToString()

        Try
            folder = folder & "/" & n_year & "/" & monthFolder

            'Create a FTP Request Object and Specfiy a Complete Path
            strFTPFilePath = "ftp://" & ServerName & "/" & folder & "/" & fileName

            Dim reqObj As FtpWebRequest = DirectCast(FtpWebRequest.Create(New Uri(strFTPFilePath)), FtpWebRequest)

            reqObj.Method = WebRequestMethods.Ftp.UploadFile
            'reqObj.EnableSsl = True

            'To access Resourse Protected,give UserName and PWD
            reqObj.Credentials = nc
            reqObj.UseBinary = True

            Dim buffer As Byte() = New Byte(fstream.Length - 1) {}
            fstream.Read(buffer, 0, buffer.Length)
            'Removed Close because the with the stream closed, it would not add data to the db
            'fstream.Close()

            'Upload file
            reqStream = reqObj.GetRequestStream()
            reqStream.Write(buffer, 0, buffer.Length)
            reqStream.Close()

            ftpWebResponse = reqObj.GetResponse()
            ftpWebResponse.Close()
            Return True

        Catch Ex As Exception
            commonFunctions.insertLogEvents(LOG_EVENT_ERROR, Ex.Message)
            Return False
        End Try

    End Function

Open in new window

0
 
LVL 18

Accepted Solution

by:
Jerry Miller earned 500 total points
ID: 39681391
I converted it to C3 using this site. http://www.developerfusion.com/tools/convert/vb-to-csharp/

public static bool UploadToFTP(Stream fstream, string fileName, string folder)
{
	Stream reqStream = default(Stream);
	FtpWebResponse ftpWebResponse = default(FtpWebResponse);
	System.Net.NetworkCredential nc = new System.Net.NetworkCredential(ID, Password);
	System.Net.CredentialCache cc = new System.Net.CredentialCache();
	string strFTPFilePath = null;
	string n_month_name = DateTime.Now.ToString("MMMM");
	string n_month_num = DateAndTime.DatePart("m", DateTime.Now).ToString();
	string n_year = DateAndTime.DatePart("yyyy", DateTime.Now).ToString();
	string monthFolder = null;
	StringBuilder builder = new StringBuilder();

	if (Strings.Len(n_month_num) == 1) {
		builder.Append("0");
	}
	builder.Append(n_month_num);
	builder.Append("_");
	builder.Append(n_month_name);
	monthFolder = builder.ToString();

	try {
		folder = folder + "/" + n_year + "/" + monthFolder;

		//Create a FTP Request Object and Specfiy a Complete Path
		strFTPFilePath = "ftp://" + ServerName + "/" + folder + "/" + fileName;

		FtpWebRequest reqObj = (FtpWebRequest)FtpWebRequest.Create(new Uri(strFTPFilePath));

		reqObj.Method = WebRequestMethods.Ftp.UploadFile;
		//reqObj.EnableSsl = True

		//To access Resourse Protected,give UserName and PWD
		reqObj.Credentials = nc;
		reqObj.UseBinary = true;

		byte[] buffer = new byte[fstream.Length];
		fstream.Read(buffer, 0, buffer.Length);
		//Removed Close because the with the stream closed, it would not add data to the db
		//fstream.Close()

		//Upload file
		reqStream = reqObj.GetRequestStream();
		reqStream.Write(buffer, 0, buffer.Length);
		reqStream.Close();

		ftpWebResponse = reqObj.GetResponse();
		ftpWebResponse.Close();
		return true;

	} catch (Exception Ex) {
		commonFunctions.insertLogEvents(LOG_EVENT_ERROR, Ex.Message);
		return false;
	}

}

Open in new window

0
 

Author Comment

by:Dovberman
ID: 39681602
I understand the principle, but have a few clarification questions:

// initialize parameters

string strSourcePath = "C:\\Develop\\Apps\\StockPro\\Data\\Changes\\";
string strSourceFile = strSourcePath + "Changes.txt";

string strSourceFileName = "Changes.txt";

        //Structure of the Changes//Changes.txt file
    //Date                  OldExchange        OldSymbol      NewExchange      NewSymbol
    //20131126      OTCBB          BRVM                       OTCBB                        ZENO
    //20131126      OTCBB          CCRY                      OTCBB                        ARTR

//Create filestream
 
FileStream fs = new FileStream(strSourceFile, FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader(fs);

// ?? How do I create the filestream from the Changes.txt file?

// Copy the file to the ftp folder

Boolean blnResponse = CopyFTPFile(fs,strSourceFileName,strSourcePath);
0
Learn by Doing. Anytime. Anywhere.

Do you like to learn by doing?
Our labs and exercises give you the chance to do just that: Learn by performing actions on real environments.

Hands-on, scenario-based labs give you experience on real environments provided by us so you don't have to worry about breaking anything.

 

Author Comment

by:Dovberman
ID: 39681692
I got it to work by making sure that the parameters were correctly structured.

Thanks,
0
 

Author Closing Comment

by:Dovberman
ID: 39681697
I got it to work by making sure that the parameters were correctly structured.

Thanks,
0
 
LVL 18

Expert Comment

by:Jerry Miller
ID: 39681722
Happy that it worked for you!
0

Featured Post

Turn Insights Into Action

You’ve already invested in ITSM tools, chat applications, automation utilities, and more. Fortify these solutions with intelligent communications so you can drive business processes forward.

With xMatters, you'll never miss a beat.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article shows how to use the open source plupload control to upload multiple images. The images are resized on the client side before uploading and the upload is done in chunks. Background I had to provide a way for user…
A theme is a collection of property settings that allow you to define the look of pages and controls, and then apply the look consistently across pages in an application. Themes can be made up of a set of elements: skins, style sheets, images, and o…
This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA. http://www.experts-exchange.com/videos/1478/Excel-Error-Handlin…
Monitoring a network: why having a policy is the best policy? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the enormous benefits of having a policy-based approach when monitoring medium and large networks. Software utilized in this v…

717 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question