Usher
Usher

Reputation: 2146

Copy files using FTP in C#

I am trying to copy file(s) using webrequest inside WCF. I need some suggestions. Are there better ways of doing this?

What kind of security issues am I going to face here?

Can I do it inside WCF or is making it separate better?

public void InsertOccured(string Name)
{
  //  Console.WriteLine("Insert Occured",Name);
    Console.WriteLine("Insert Occured, {0}", Name);
   // FTP request to download the file from FTP Location
    FtpWebRequest reqFTP;

    try
    {
        string FilePath;
        string FileName = Name;

        //use Switch statement to identify the ftpServerIP

        FileStream outputStream = new FileStream(FilePath + "\\" + FileName, FileMode.Create);
        reqFTP= (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpserverIp + FileName));
        reqFTP.Method= WebRequestMethods.Ftp.DownloadFile;
        reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
        FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
        Stream ftpStream = response.GetResponseStream();
        long cl = response.ContentLength;
        int bufferSize = 2048;
        int readCount;
        byte[] buffer = new byte[bufferSize];
        readCount = ftpStream.Read(buffer, 0, bufferSize);
        while (readCount > 0)
        {
            outputStream.Write(buffer, 0, readCount);
            readCount = ftpStream.Read(buffer, 0, bufferSize);
        }

        ftpStream.Close();
        outputStream.Close();
        response.Close();

    }
    catch (Exception ex)
    {
        Console.WriteLine(ex);
    }
}

Upvotes: 1

Views: 3493

Answers (2)

DotNetUser
DotNetUser

Reputation: 6612

Its always better to make it separate but I don't know much about security issues with WCF however you could use this code to read responseStream, you should be using "using" to have framework manage disposing the stream properly

    try
        {
            byte[] buffer = new byte[4155]; 
            byte[] newBuffer;
            int readSize = 0;
            FileStream outputStream = new FileStream(FilePath + "\\" + FileName, FileMode.Create);
            int i = 0;
            using (Stream input = response.GetResponseStream())
            {
                    readSize = input.Read(buffer, 0, buffer.Length);
                    if (readSize > 0)
                    {
                        newBuffer = new byte[readSize];
                        Array.Copy(buffer, newBuffer, readSize);
                        outputStream.Write(newBuffer.ToArray(), 0, readSize);
                    }
                outputStream.Close();
            } 

Upvotes: 1

Scott Smith
Scott Smith

Reputation: 1863

Using FTP is not the most secure. Username, passwords, and all data are sent in the clear. If you are concerned about security you should consider using SFTP.

Upvotes: 4

Related Questions