FTP Upload

M

MDB

Anyone have any pointers / links / examples on how to upload files through
FTP? I am currently using the built in file upload control however it seems
to take a very long time to upload files and would like to explore other
ways of doing it. Any pointers or suggestions would greatly be appreciated.
 
M

Misbah Arefin

i got this from some site a couple of years back (dont recall which site)

/////////////////////
using System;
using System.Net;
using System.IO;
using System.Text;
using System.Net.Sockets;

namespace SampleCode
{
public class clsFTP
{
#region "Class Variable Declarations"
private string m_sRemoteHost, m_sRemotePath, m_sRemoteUser;
private string m_sRemotePassword, m_sMess;
private int m_iRemotePort, m_iBytes;
private Socket m_objClientSocket;

private int m_iRetValue;
private bool m_bLoggedIn;
private string m_sMes, m_sReply;

//set the size of the packet that is used to read and to write data to the
FTP server to the following specified size.
public const int BLOCK_SIZE = 512;
private byte[] m_aBuffer = new byte[BLOCK_SIZE];
private Encoding ASCII = Encoding.ASCII;
public bool flag_bool;
//general variable declaration
private string m_sMessageString;
#endregion

#region "Class Constructors"

//main class constructor
public clsFTP()
{
m_sRemoteHost = "microsoft";
m_sRemotePath = ".";
m_sRemoteUser = "anonymous";
m_sRemotePassword = "";
m_sMessageString = "";
m_iRemotePort = 21;
m_bLoggedIn = false;
}

//parameterized constructor
public clsFTP(string sRemoteHost, string sRemotePath, string sRemoteUser,
string sRemotePassword, int iRemotePort)
{
m_sRemoteHost = sRemoteHost;
m_sRemotePath = sRemotePath;
m_sRemoteUser = sRemoteUser;
m_sRemotePassword = sRemotePassword;
m_sMessageString = "";
m_iRemotePort = 21;
m_bLoggedIn = false;
}
#endregion

#region "Public Properties"

//set or get the name of the FTP server that you want to connect.
public string RemoteHostFTPServer
{
//get the name of the FTP server.
get{return m_sRemoteHost;}
//set the name of the FTP server.
set{m_sRemoteHost = value;}
}

//set or get the FTP Port Number of the FTP server that you want to connect.
public int RemotePort
{
//get the FTP Port Number.
get{return m_iRemotePort;}
//set the FTP Port Number.
set{m_iRemotePort = value;}
}

//set or get the remote path of the FTP server that you want to connect.
public string RemotePath
{
//get the remote path.
get{return m_sRemotePath;}
//set the remote path.
set{m_sRemotePath = value;}
}

//set or get the remote password of the FTP server that you want to connect.
public string RemotePassword
{
get{return m_sRemotePassword;}
set{m_sRemotePassword = value;}
}

//set or get the remote user of the FTP server that you want to connect.
public string RemoteUser
{
get{return m_sRemoteUser;}
set{m_sRemoteUser = value;}
}

//set the class MessageString.
public string MessageString
{
get{return m_sMessageString;}
set{m_sMessageString = value;}
}
#endregion

#region "Public Subs and Functions"

//return a list of files in a string array from the file system.
public string[] GetFileList(string sMask)
{
Socket cSocket;
int bytes;
char seperator = '\n';
string[] mess;

m_sMes = "";
//check if you are logged on to the FTP server.
if(!(m_bLoggedIn))
{
Login();
}

cSocket = CreateDataSocket();
//send an FTP command,
SendCommand("NLST " + sMask);

if(!(m_iRetValue == 150 || m_iRetValue == 125))
{
MessageString = m_sReply;
throw new IOException(m_sReply.Substring(4));
}

m_sMes = "";
while(true)
{
Array.Clear(m_aBuffer, 0, m_aBuffer.Length);
bytes = cSocket.Receive(m_aBuffer, m_aBuffer.Length, 0);
m_sMes += ASCII.GetString(m_aBuffer, 0, bytes);

if(bytes < m_aBuffer.Length)
{
break;
}
}

mess = m_sMes.Split(seperator);
cSocket.Close();
ReadReply();

if(m_iRetValue != 226)
{
MessageString = m_sReply;
throw new IOException(m_sReply.Substring(4));
}

return mess;
}

//get the size of the file on the FTP server.
public long GetFileSize(string sFileName)
{
long size;

if(!(m_bLoggedIn))
{
Login();
}
//send an FTP command.
SendCommand("SIZE " + sFileName);
size = 0;

if(m_iRetValue == 213)
{
size = long.Parse(m_sReply.Substring(4));
}
else
{
MessageString = m_sReply;
throw new IOException(m_sReply.Substring(4));
}

return size;
}

//log on to the FTP server.
public bool Login()
{
m_objClientSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);

IPEndPoint ep = new IPEndPoint(Dns.Resolve(m_sRemoteHost).AddressList[0],
m_iRemotePort);

try
{
m_objClientSocket.Connect(ep);
}
catch(Exception ex)
{
MessageString = m_sReply;
throw new IOException("Cannot connect to remote server");
}

ReadReply();
if(m_iRetValue != 220)
{
CloseConnection();
MessageString = m_sReply;
throw new IOException(m_sReply.Substring(4));
}
//send an FTP command to send a user logon ID to the server.
SendCommand("USER " + m_sRemoteUser);
if(!(m_iRetValue == 331 || m_iRetValue == 230))
{
Cleanup();
MessageString = m_sReply;
throw new IOException(m_sReply.Substring(4));
}

if(m_iRetValue != 230)
{
//send an FTP command to send a user logon password to the server.
SendCommand("PASS " + m_sRemotePassword);
if(!(m_iRetValue == 230 || m_iRetValue == 202))
{
Cleanup();
MessageString = m_sReply;
throw new IOException(m_sReply.Substring(4));
}
}

m_bLoggedIn = true;
//call the ChangeDirectory user-defined function to change the folder to
the remote FTP folder that is mapped.
ChangeDirectory(m_sRemotePath);

//return the final result.
return m_bLoggedIn;
}

//if the value of mode is true, set the binary mode for downloads.
Otherwise, set ASCII mode.
public void SetBinaryMode(bool bMode)
{
if(bMode)
{
//send the FTP command to set the binary mode.
//(TYPE is an FTP command that is used to specify representation type.)
SendCommand("TYPE I");
}
else
{
//send the FTP command to set ASCII mode.
//(TYPE is a FTP command that is used to specify representation type.)
SendCommand("TYPE A");
}

if(m_iRetValue != 200)
{
MessageString = m_sReply;
throw new IOException(m_sReply.Substring(4));
}
}

//download a file to the local folder of the assembly, and keep the same
file name.
public void DownloadFile(string sFileName)
{
DownloadFile(sFileName, "", false);
}
//download a remote file to the local folder of the assembly, and keep the
same file name.
public void DownloadFile(string sFileName, bool bResume)
{
DownloadFile(sFileName, "", bResume);
}
//download a remote file to a local file name. You must include a path.
//the local file name will be created or will be overwritten, but the path
must exist.
public void DownloadFile(string sFileName, string sLocalFileName)
{
DownloadFile(sFileName, sLocalFileName, false);
}
//download a remote file to a local file name and include a path. Then,
set the resume flag. The local file name will be created or will be
overwritten, but the path must exist.
public void DownloadFile(string sFileName, string sLocalFileName, bool
bResume)
{
Stream st;
FileStream output;
Socket cSocket;
long offset, npos;

if(!(m_bLoggedIn))
{
Login();
}

SetBinaryMode(true);

if(sLocalFileName.Equals(""))
{
sLocalFileName = sFileName;
}

if(!(File.Exists(sLocalFileName)))
{
st = File.Create(sLocalFileName);
st.Close();
}

output = new FileStream(sLocalFileName, FileMode.Open);
cSocket = CreateDataSocket();
offset = 0;

if(bResume)
{
offset = output.Length;

if(offset > 0)
{
//send an FTP command to restart.
SendCommand("REST " + offset);
if(m_iRetValue != 350)
{
offset = 0;
}
}

if(offset > 0)
{
npos = output.Seek(offset, SeekOrigin.Begin);
}
}
//send an FTP command to retrieve a file.
SendCommand("RETR " + sFileName);

if(!(m_iRetValue == 150 || m_iRetValue == 125))
{
MessageString = m_sReply;
throw new IOException(m_sReply.Substring(4));
}

while(true)
{
Array.Clear(m_aBuffer, 0, m_aBuffer.Length);
m_iBytes = cSocket.Receive(m_aBuffer, m_aBuffer.Length, 0);
output.Write(m_aBuffer, 0, m_iBytes);

if(m_iBytes <= 0)
{
break;
}
}

output.Close();
if(cSocket.Connected)
{
cSocket.Close();
}

ReadReply();
if(!(m_iRetValue == 226 || m_iRetValue == 250))
{
MessageString = m_sReply;
throw new IOException(m_sReply.Substring(4));
}
}

//this is a function that is used to upload a file from your local hard
disk to your FTP site.
public void UploadFile(string sFileName)
{
UploadFile(sFileName, false);
}
//this is a function that is used to upload a file from your local hard
disk to your FTP site and then set the resume flag.
public void UploadFile(string sFileName, bool bResume)
{
Socket cSocket;
long offset;
FileStream input;
bool bFileNotFound;

if(!(m_bLoggedIn))
{
Login();
}

cSocket = CreateDataSocket();
offset = 0;

if(bResume)
{
try
{
SetBinaryMode(true);
offset = GetFileSize(sFileName);
}
catch(Exception ex)
{
offset = 0;
}
}

if(offset > 0)
{
SendCommand("REST " + offset);
if(m_iRetValue != 350)
{
//the remote server may not support resuming.
offset = 0;
}
}
//send an FTP command to store a file.
SendCommand("STOR " + Path.GetFileName(sFileName));
if(!(m_iRetValue == 125 || m_iRetValue == 150))
{
MessageString = m_sReply;
throw new IOException(m_sReply.Substring(4));
}

//check to see if the file exists before the upload.
bFileNotFound = false;
if(File.Exists(sFileName))
{
//open the input stream to read the source file.
input = new FileStream(sFileName, FileMode.Open);
if(offset != 0)
{
input.Seek(offset, SeekOrigin.Begin);
}

//upload the file.
m_iBytes = input.Read(m_aBuffer, 0, m_aBuffer.Length);
while(m_iBytes > 0)
{
cSocket.Send(m_aBuffer, m_iBytes, 0);
m_iBytes = input.Read(m_aBuffer, 0, m_aBuffer.Length);
}
input.Close();
}
else
{
bFileNotFound = true;
}

if(cSocket.Connected)
{
cSocket.Close();
}

//check the return value if the file was not found.
if(bFileNotFound)
{
MessageString = m_sReply;
throw new IOException("The file: " + sFileName + " was not found." + "
Cannot upload the file to the FTP site.");
}

ReadReply();
if(!(m_iRetValue == 226 || m_iRetValue == 250))
{
MessageString = m_sReply;
throw new IOException(m_sReply.Substring(4));
}
}

//delete a file from the remote FTP server.
public bool DeleteFile(string sFileName)
{
bool bResult;

bResult = true;
if(!(m_bLoggedIn))
{
Login();
}
//send an FTP command to delete a file.
SendCommand("DELE " + sFileName);
if(m_iRetValue != 250)
{
bResult = false;
MessageString = m_sReply;
}

//return the final result.
return bResult;
}

//rename a file on the remote FTP server.
public bool RenameFile(string sOldFileName, string sNewFileName)
{
bool bResult;

bResult = true;
if(!(m_bLoggedIn))
{
Login();
}
//send an FTP command to rename a file.
SendCommand("RNFR " + sOldFileName);
if(m_iRetValue != 350)
{
MessageString = m_sReply;
throw new IOException(m_sReply.Substring(4));
}

//send an FTP command to rename a file to a file name. It will overwrite
if newFileName exists.
SendCommand("RNTO " + sNewFileName);
if(m_iRetValue != 250)
{
MessageString = m_sReply;
throw new IOException(m_sReply.Substring(4));
}
//return the final result.
return bResult;
}

//this is a function that is used to create a folder on the remote FTP
server.
public bool CreateDirectory(string sDirName)
{
bool bResult;

bResult = true;
if(!(m_bLoggedIn))
{
Login();
}
//send an FTP command to make a folder on the FTP server.
SendCommand("MKD " + sDirName);
if(m_iRetValue != 257)
{
bResult = false;
MessageString = m_sReply;
}

//return the final result.
return bResult;
}

//this is a function that is used to delete a folder on the remote FTP
server.
public bool RemoveDirectory(string sDirName)
{
bool bResult;

bResult = true;
//check if you are logged on to the FTP server.
if(!(m_bLoggedIn))
{
Login();
}
//send an FTP command to remove a folder on the FTP server.
SendCommand("RMD " + sDirName);
if(m_iRetValue != 250)
{
bResult = false;
MessageString = m_sReply;
}

//return the final result.
return bResult;
}

//this is a function that is used to change the current working folder on
the remote FTP server.
public bool ChangeDirectory(string sDirName)
{
bool bResult;

bResult = true;
//ceck if you are in the root directory.
if(sDirName.Equals("."))
{
return bResult;
}
//check if you are logged on to the FTP server.
if(!(m_bLoggedIn))
{
Login();
}
//send an FTP command to change the folder on the FTP server.
SendCommand("CWD " + sDirName);
if(m_iRetValue != 250)
{
bResult = false;
MessageString = m_sReply;
}

m_sRemotePath = sDirName;

//return the final result.
return bResult;
}

//close the FTP connection of the remote server.
public void CloseConnection()
{
if(!(m_objClientSocket == null))
{
//send an FTP command to end an FTP server system.
SendCommand("QUIT");
}

Cleanup();
}
#endregion

#region "Private Subs and Functions"
//read the reply from the FTP server.
private void ReadReply()
{
m_sMes = "";
m_sReply = ReadLine();
m_iRetValue = int.Parse(m_sReply.Substring(0, 3));
}

//clean up some variables.
private void Cleanup()
{
if(!(m_objClientSocket == null))
{
m_objClientSocket.Close();
m_objClientSocket = null;
}

m_bLoggedIn = false;
}

//read a line from the FTP server.
private string ReadLine()
{
return ReadLine(false);
}

private string ReadLine(bool bClearMes)
{
char seperator = '\n';
string[] mess;

if(bClearMes)
{
m_sMes = "";
}
while(true)
{
Array.Clear(m_aBuffer, 0, BLOCK_SIZE);
m_iBytes = m_objClientSocket.Receive(m_aBuffer, m_aBuffer.Length, 0);
m_sMes += ASCII.GetString(m_aBuffer, 0, m_iBytes);
if(m_iBytes < m_aBuffer.Length)
{
break;
}
}

mess = m_sMes.Split(seperator);
if(m_sMes.Length > 2)
{
m_sMes = mess[mess.Length - 2];
}
else
{
m_sMes = mess[0];
}

if(!(m_sMes.Substring(3, 1).Equals(" ")))
{
return ReadLine(true);
}

return m_sMes;
}

//this is a function that is used to send a command to the FTP server that
you are connected to.
private void SendCommand(string sCommand)
{
sCommand = sCommand + '\n';
byte[] cmdbytes = ASCII.GetBytes(sCommand);
m_objClientSocket.Send(cmdbytes, cmdbytes.Length, 0);
ReadReply();
}

//create a data socket.
private Socket CreateDataSocket()
{
int index1, index2, len;
int partCount, i, port;
string ipData, buf, ipAddress;
int[] parts = new int[6];
char ch;
Socket s;
IPEndPoint ep;
//send an FTP command to use a passive data connection.
SendCommand("PASV");
if(m_iRetValue != 227)
{
MessageString = m_sReply;
throw new IOException(m_sReply.Substring(4));
}

index1 = m_sReply.IndexOf("(");
index2 = m_sReply.IndexOf(")");
ipData = m_sReply.Substring(index1 + 1, index2 - index1 - 1);

len = ipData.Length;
partCount = 0;
buf = "";

for(i = 0; i < len && partCount <= 6; i++)
{
ch = char.Parse(ipData.Substring(i, 1));
if(char.IsDigit(ch))
{
buf += ch;
}
else
{
if(ch != ',')
{
MessageString = m_sReply;
throw new IOException("Malformed PASV reply: " + m_sReply);
}
}

if((ch == ',') || (i + 1 == len))
{
try
{
parts[partCount] = int.Parse(buf);
partCount += 1;
buf = "";
}
catch(Exception ex)
{
MessageString = m_sReply;
throw new IOException("Malformed PASV reply: " + m_sReply);
}
}
}

ipAddress = parts[0] + "." + parts[1] + "." + parts[2] + "." + parts[3];

port = parts[4] << 8;

//determine the data port number.
port = port + parts[5];

s = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp);
ep = new IPEndPoint(Dns.Resolve(ipAddress).AddressList[0], port);

try
{
s.Connect(ep);
}
catch(Exception ex)
{
MessageString = m_sReply;
throw new IOException("Cannot connect to remote server");
//if you cannot connect to the FTP server that is specified, make the
boolean variable false.
flag_bool = false;
}
//if you can connect to the FTP server that is specified, make the
boolean variable true.
flag_bool = true;
return s;
}
#endregion

// #region TestFTP
// private void TestFTP()
// {
// //create an instance of the FTP class that is created.
// clsFTP ff;
//
// try
// {
// //pass values to the constructor. These values can be overridden by
setting the appropriate properties on the instance of the clsFTP class. The
third parameter is the user name. The FTP site is accessed with the user
name. If there is no specific user name, the user name can be anonymous. The
fourth parameter is the password. The FTP server is accessed with the
password. The fifth parameter is the port of the FTP server. The port of the
FTP server is typically 21.
//
// ff = new clsFTP(StrIP, "/Myfolder/", "anonymous", "", 21);
//
// //try to log on to the FTP server.
// if(ff.Login() == true)
// {
// //change the directory on your FTP site.
// if(ff.ChangeDirectory("MyOwnFolder") == true)
// {
// //successful changing the directory
// ff.CreateDirectory("FTPFOLDERNEW");
// ff.ChangeDirectory("FTPFOLDERNEW");
//
// ff.SetBinaryMode(true);
//
// //upload a file from your local hard disk to the FTP site.
// ff.UploadFile("C:\Test\Example1.txt")
// ff.UploadFile("C:\Test\Example2.doc");
// ff.UploadFile("C:\Test\Example3.doc");
//
// //download a file from the FTP site to your local hard disk.
// ff.DownloadFile("Example2.doc", "C:\Test\Example2.doc");
//
// //remove a file from the FTP site.
// ff.DeleteFile("Example1.txt");
//
// //rename a file on the FTP site.
// ff.RenameFile("Example3.doc", "Example3_new.doc");
//
// //change the directory to one directory before.
// ff.ChangeDirectory("..");
// }
//
// //create a new directory.
// ff.CreateDirectory("MyOwnFolderNew");
//
// //remove the directory that is created on the FTP site.
// ff.RemoveDirectory("MyOwnFolderNew");
// }
// }
// catch(System.Exception ex)
// {
// }
// finally
// {
// //always close the connection to make sure that there are not any
not-in-use FTP connections. Check if you are logged on to the FTP server and
then close the connection.
// if(ff.flag_bool == true)
// {
// ff.CloseConnection();
// }
// }
// }
// #endregion

}
}
 
R

rosoft

Hi

There is a FTP plugin I have used for Delphi 32 bit programming but it is
also available for .Net programing. Take a look at the PowerTCP tools at
www.dart.com. They cost a bit but the 32 bit DLL is very good. You can
control it very nice. You can basicly set time outs and very thing as you
want. I build a system that was installed on cient PC that sent ftp files to
a Linux server. If the connection dropped after an hour or to and was gone
for 3 hours I managed to get the program up and continue with the upload.
The key is waht happens when an upload fails if you upload 800 MB files. The
upload will in 99.9% of the cased have at least one timeout from the
Internet. If the device makes an exception you must be able to wait for tha
exception. I stronly recomend that you take a look at the Dart tools. They
cost abit but well worth the money.

IS the ftp program going to be on the webserver or will it be installed on
the clients computers.

Lars
 
M

MDB

Thanks

Misbah Arefin said:
i got this from some site a couple of years back (dont recall which site)

/////////////////////
using System;
using System.Net;
using System.IO;
using System.Text;
using System.Net.Sockets;

namespace SampleCode
{
public class clsFTP
{
#region "Class Variable Declarations"
private string m_sRemoteHost, m_sRemotePath, m_sRemoteUser;
private string m_sRemotePassword, m_sMess;
private int m_iRemotePort, m_iBytes;
private Socket m_objClientSocket;

private int m_iRetValue;
private bool m_bLoggedIn;
private string m_sMes, m_sReply;

//set the size of the packet that is used to read and to write data to the
FTP server to the following specified size.
public const int BLOCK_SIZE = 512;
private byte[] m_aBuffer = new byte[BLOCK_SIZE];
private Encoding ASCII = Encoding.ASCII;
public bool flag_bool;
//general variable declaration
private string m_sMessageString;
#endregion

#region "Class Constructors"

//main class constructor
public clsFTP()
{
m_sRemoteHost = "microsoft";
m_sRemotePath = ".";
m_sRemoteUser = "anonymous";
m_sRemotePassword = "";
m_sMessageString = "";
m_iRemotePort = 21;
m_bLoggedIn = false;
}

//parameterized constructor
public clsFTP(string sRemoteHost, string sRemotePath, string sRemoteUser,
string sRemotePassword, int iRemotePort)
{
m_sRemoteHost = sRemoteHost;
m_sRemotePath = sRemotePath;
m_sRemoteUser = sRemoteUser;
m_sRemotePassword = sRemotePassword;
m_sMessageString = "";
m_iRemotePort = 21;
m_bLoggedIn = false;
}
#endregion

#region "Public Properties"

//set or get the name of the FTP server that you want to connect.
public string RemoteHostFTPServer
{
//get the name of the FTP server.
get{return m_sRemoteHost;}
//set the name of the FTP server.
set{m_sRemoteHost = value;}
}

//set or get the FTP Port Number of the FTP server that you want to
connect.
public int RemotePort
{
//get the FTP Port Number.
get{return m_iRemotePort;}
//set the FTP Port Number.
set{m_iRemotePort = value;}
}

//set or get the remote path of the FTP server that you want to connect.
public string RemotePath
{
//get the remote path.
get{return m_sRemotePath;}
//set the remote path.
set{m_sRemotePath = value;}
}

//set or get the remote password of the FTP server that you want to
connect.
public string RemotePassword
{
get{return m_sRemotePassword;}
set{m_sRemotePassword = value;}
}

//set or get the remote user of the FTP server that you want to connect.
public string RemoteUser
{
get{return m_sRemoteUser;}
set{m_sRemoteUser = value;}
}

//set the class MessageString.
public string MessageString
{
get{return m_sMessageString;}
set{m_sMessageString = value;}
}
#endregion

#region "Public Subs and Functions"

//return a list of files in a string array from the file system.
public string[] GetFileList(string sMask)
{
Socket cSocket;
int bytes;
char seperator = '\n';
string[] mess;

m_sMes = "";
//check if you are logged on to the FTP server.
if(!(m_bLoggedIn))
{
Login();
}

cSocket = CreateDataSocket();
//send an FTP command,
SendCommand("NLST " + sMask);

if(!(m_iRetValue == 150 || m_iRetValue == 125))
{
MessageString = m_sReply;
throw new IOException(m_sReply.Substring(4));
}

m_sMes = "";
while(true)
{
Array.Clear(m_aBuffer, 0, m_aBuffer.Length);
bytes = cSocket.Receive(m_aBuffer, m_aBuffer.Length, 0);
m_sMes += ASCII.GetString(m_aBuffer, 0, bytes);

if(bytes < m_aBuffer.Length)
{
break;
}
}

mess = m_sMes.Split(seperator);
cSocket.Close();
ReadReply();

if(m_iRetValue != 226)
{
MessageString = m_sReply;
throw new IOException(m_sReply.Substring(4));
}

return mess;
}

//get the size of the file on the FTP server.
public long GetFileSize(string sFileName)
{
long size;

if(!(m_bLoggedIn))
{
Login();
}
//send an FTP command.
SendCommand("SIZE " + sFileName);
size = 0;

if(m_iRetValue == 213)
{
size = long.Parse(m_sReply.Substring(4));
}
else
{
MessageString = m_sReply;
throw new IOException(m_sReply.Substring(4));
}

return size;
}

//log on to the FTP server.
public bool Login()
{
m_objClientSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);

IPEndPoint ep = new IPEndPoint(Dns.Resolve(m_sRemoteHost).AddressList[0],
m_iRemotePort);

try
{
m_objClientSocket.Connect(ep);
}
catch(Exception ex)
{
MessageString = m_sReply;
throw new IOException("Cannot connect to remote server");
}

ReadReply();
if(m_iRetValue != 220)
{
CloseConnection();
MessageString = m_sReply;
throw new IOException(m_sReply.Substring(4));
}
//send an FTP command to send a user logon ID to the server.
SendCommand("USER " + m_sRemoteUser);
if(!(m_iRetValue == 331 || m_iRetValue == 230))
{
Cleanup();
MessageString = m_sReply;
throw new IOException(m_sReply.Substring(4));
}

if(m_iRetValue != 230)
{
//send an FTP command to send a user logon password to the server.
SendCommand("PASS " + m_sRemotePassword);
if(!(m_iRetValue == 230 || m_iRetValue == 202))
{
Cleanup();
MessageString = m_sReply;
throw new IOException(m_sReply.Substring(4));
}
}

m_bLoggedIn = true;
//call the ChangeDirectory user-defined function to change the folder to
the remote FTP folder that is mapped.
ChangeDirectory(m_sRemotePath);

//return the final result.
return m_bLoggedIn;
}

//if the value of mode is true, set the binary mode for downloads.
Otherwise, set ASCII mode.
public void SetBinaryMode(bool bMode)
{
if(bMode)
{
//send the FTP command to set the binary mode.
//(TYPE is an FTP command that is used to specify representation type.)
SendCommand("TYPE I");
}
else
{
//send the FTP command to set ASCII mode.
//(TYPE is a FTP command that is used to specify representation type.)
SendCommand("TYPE A");
}

if(m_iRetValue != 200)
{
MessageString = m_sReply;
throw new IOException(m_sReply.Substring(4));
}
}

//download a file to the local folder of the assembly, and keep the same
file name.
public void DownloadFile(string sFileName)
{
DownloadFile(sFileName, "", false);
}
//download a remote file to the local folder of the assembly, and keep the
same file name.
public void DownloadFile(string sFileName, bool bResume)
{
DownloadFile(sFileName, "", bResume);
}
//download a remote file to a local file name. You must include a path.
//the local file name will be created or will be overwritten, but the path
must exist.
public void DownloadFile(string sFileName, string sLocalFileName)
{
DownloadFile(sFileName, sLocalFileName, false);
}
//download a remote file to a local file name and include a path. Then,
set the resume flag. The local file name will be created or will be
overwritten, but the path must exist.
public void DownloadFile(string sFileName, string sLocalFileName, bool
bResume)
{
Stream st;
FileStream output;
Socket cSocket;
long offset, npos;

if(!(m_bLoggedIn))
{
Login();
}

SetBinaryMode(true);

if(sLocalFileName.Equals(""))
{
sLocalFileName = sFileName;
}

if(!(File.Exists(sLocalFileName)))
{
st = File.Create(sLocalFileName);
st.Close();
}

output = new FileStream(sLocalFileName, FileMode.Open);
cSocket = CreateDataSocket();
offset = 0;

if(bResume)
{
offset = output.Length;

if(offset > 0)
{
//send an FTP command to restart.
SendCommand("REST " + offset);
if(m_iRetValue != 350)
{
offset = 0;
}
}

if(offset > 0)
{
npos = output.Seek(offset, SeekOrigin.Begin);
}
}
//send an FTP command to retrieve a file.
SendCommand("RETR " + sFileName);

if(!(m_iRetValue == 150 || m_iRetValue == 125))
{
MessageString = m_sReply;
throw new IOException(m_sReply.Substring(4));
}

while(true)
{
Array.Clear(m_aBuffer, 0, m_aBuffer.Length);
m_iBytes = cSocket.Receive(m_aBuffer, m_aBuffer.Length, 0);
output.Write(m_aBuffer, 0, m_iBytes);

if(m_iBytes <= 0)
{
break;
}
}

output.Close();
if(cSocket.Connected)
{
cSocket.Close();
}

ReadReply();
if(!(m_iRetValue == 226 || m_iRetValue == 250))
{
MessageString = m_sReply;
throw new IOException(m_sReply.Substring(4));
}
}

//this is a function that is used to upload a file from your local hard
disk to your FTP site.
public void UploadFile(string sFileName)
{
UploadFile(sFileName, false);
}
//this is a function that is used to upload a file from your local hard
disk to your FTP site and then set the resume flag.
public void UploadFile(string sFileName, bool bResume)
{
Socket cSocket;
long offset;
FileStream input;
bool bFileNotFound;

if(!(m_bLoggedIn))
{
Login();
}

cSocket = CreateDataSocket();
offset = 0;

if(bResume)
{
try
{
SetBinaryMode(true);
offset = GetFileSize(sFileName);
}
catch(Exception ex)
{
offset = 0;
}
}

if(offset > 0)
{
SendCommand("REST " + offset);
if(m_iRetValue != 350)
{
//the remote server may not support resuming.
offset = 0;
}
}
//send an FTP command to store a file.
SendCommand("STOR " + Path.GetFileName(sFileName));
if(!(m_iRetValue == 125 || m_iRetValue == 150))
{
MessageString = m_sReply;
throw new IOException(m_sReply.Substring(4));
}

//check to see if the file exists before the upload.
bFileNotFound = false;
if(File.Exists(sFileName))
{
//open the input stream to read the source file.
input = new FileStream(sFileName, FileMode.Open);
if(offset != 0)
{
input.Seek(offset, SeekOrigin.Begin);
}

//upload the file.
m_iBytes = input.Read(m_aBuffer, 0, m_aBuffer.Length);
while(m_iBytes > 0)
{
cSocket.Send(m_aBuffer, m_iBytes, 0);
m_iBytes = input.Read(m_aBuffer, 0, m_aBuffer.Length);
}
input.Close();
}
else
{
bFileNotFound = true;
}

if(cSocket.Connected)
{
cSocket.Close();
}

//check the return value if the file was not found.
if(bFileNotFound)
{
MessageString = m_sReply;
throw new IOException("The file: " + sFileName + " was not found." + "
Cannot upload the file to the FTP site.");
}

ReadReply();
if(!(m_iRetValue == 226 || m_iRetValue == 250))
{
MessageString = m_sReply;
throw new IOException(m_sReply.Substring(4));
}
}

//delete a file from the remote FTP server.
public bool DeleteFile(string sFileName)
{
bool bResult;

bResult = true;
if(!(m_bLoggedIn))
{
Login();
}
//send an FTP command to delete a file.
SendCommand("DELE " + sFileName);
if(m_iRetValue != 250)
{
bResult = false;
MessageString = m_sReply;
}

//return the final result.
return bResult;
}

//rename a file on the remote FTP server.
public bool RenameFile(string sOldFileName, string sNewFileName)
{
bool bResult;

bResult = true;
if(!(m_bLoggedIn))
{
Login();
}
//send an FTP command to rename a file.
SendCommand("RNFR " + sOldFileName);
if(m_iRetValue != 350)
{
MessageString = m_sReply;
throw new IOException(m_sReply.Substring(4));
}

//send an FTP command to rename a file to a file name. It will overwrite
if newFileName exists.
SendCommand("RNTO " + sNewFileName);
if(m_iRetValue != 250)
{
MessageString = m_sReply;
throw new IOException(m_sReply.Substring(4));
}
//return the final result.
return bResult;
}

//this is a function that is used to create a folder on the remote FTP
server.
public bool CreateDirectory(string sDirName)
{
bool bResult;

bResult = true;
if(!(m_bLoggedIn))
{
Login();
}
//send an FTP command to make a folder on the FTP server.
SendCommand("MKD " + sDirName);
if(m_iRetValue != 257)
{
bResult = false;
MessageString = m_sReply;
}

//return the final result.
return bResult;
}

//this is a function that is used to delete a folder on the remote FTP
server.
public bool RemoveDirectory(string sDirName)
{
bool bResult;

bResult = true;
//check if you are logged on to the FTP server.
if(!(m_bLoggedIn))
{
Login();
}
//send an FTP command to remove a folder on the FTP server.
SendCommand("RMD " + sDirName);
if(m_iRetValue != 250)
{
bResult = false;
MessageString = m_sReply;
}

//return the final result.
return bResult;
}

//this is a function that is used to change the current working folder on
the remote FTP server.
public bool ChangeDirectory(string sDirName)
{
bool bResult;

bResult = true;
//ceck if you are in the root directory.
if(sDirName.Equals("."))
{
return bResult;
}
//check if you are logged on to the FTP server.
if(!(m_bLoggedIn))
{
Login();
}
//send an FTP command to change the folder on the FTP server.
SendCommand("CWD " + sDirName);
if(m_iRetValue != 250)
{
bResult = false;
MessageString = m_sReply;
}

m_sRemotePath = sDirName;

//return the final result.
return bResult;
}

//close the FTP connection of the remote server.
public void CloseConnection()
{
if(!(m_objClientSocket == null))
{
//send an FTP command to end an FTP server system.
SendCommand("QUIT");
}

Cleanup();
}
#endregion

#region "Private Subs and Functions"
//read the reply from the FTP server.
private void ReadReply()
{
m_sMes = "";
m_sReply = ReadLine();
m_iRetValue = int.Parse(m_sReply.Substring(0, 3));
}

//clean up some variables.
private void Cleanup()
{
if(!(m_objClientSocket == null))
{
m_objClientSocket.Close();
m_objClientSocket = null;
}

m_bLoggedIn = false;
}

//read a line from the FTP server.
private string ReadLine()
{
return ReadLine(false);
}

private string ReadLine(bool bClearMes)
{
char seperator = '\n';
string[] mess;

if(bClearMes)
{
m_sMes = "";
}
while(true)
{
Array.Clear(m_aBuffer, 0, BLOCK_SIZE);
m_iBytes = m_objClientSocket.Receive(m_aBuffer, m_aBuffer.Length, 0);
m_sMes += ASCII.GetString(m_aBuffer, 0, m_iBytes);
if(m_iBytes < m_aBuffer.Length)
{
break;
}
}

mess = m_sMes.Split(seperator);
if(m_sMes.Length > 2)
{
m_sMes = mess[mess.Length - 2];
}
else
{
m_sMes = mess[0];
}

if(!(m_sMes.Substring(3, 1).Equals(" ")))
{
return ReadLine(true);
}

return m_sMes;
}

//this is a function that is used to send a command to the FTP server that
you are connected to.
private void SendCommand(string sCommand)
{
sCommand = sCommand + '\n';
byte[] cmdbytes = ASCII.GetBytes(sCommand);
m_objClientSocket.Send(cmdbytes, cmdbytes.Length, 0);
ReadReply();
}

//create a data socket.
private Socket CreateDataSocket()
{
int index1, index2, len;
int partCount, i, port;
string ipData, buf, ipAddress;
int[] parts = new int[6];
char ch;
Socket s;
IPEndPoint ep;
//send an FTP command to use a passive data connection.
SendCommand("PASV");
if(m_iRetValue != 227)
{
MessageString = m_sReply;
throw new IOException(m_sReply.Substring(4));
}

index1 = m_sReply.IndexOf("(");
index2 = m_sReply.IndexOf(")");
ipData = m_sReply.Substring(index1 + 1, index2 - index1 - 1);

len = ipData.Length;
partCount = 0;
buf = "";

for(i = 0; i < len && partCount <= 6; i++)
{
ch = char.Parse(ipData.Substring(i, 1));
if(char.IsDigit(ch))
{
buf += ch;
}
else
{
if(ch != ',')
{
MessageString = m_sReply;
throw new IOException("Malformed PASV reply: " + m_sReply);
}
}

if((ch == ',') || (i + 1 == len))
{
try
{
parts[partCount] = int.Parse(buf);
partCount += 1;
buf = "";
}
catch(Exception ex)
{
MessageString = m_sReply;
throw new IOException("Malformed PASV reply: " + m_sReply);
}
}
}

ipAddress = parts[0] + "." + parts[1] + "." + parts[2] + "." + parts[3];

port = parts[4] << 8;

//determine the data port number.
port = port + parts[5];

s = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp);
ep = new IPEndPoint(Dns.Resolve(ipAddress).AddressList[0], port);

try
{
s.Connect(ep);
}
catch(Exception ex)
{
MessageString = m_sReply;
throw new IOException("Cannot connect to remote server");
//if you cannot connect to the FTP server that is specified, make the
boolean variable false.
flag_bool = false;
}
//if you can connect to the FTP server that is specified, make the
boolean variable true.
flag_bool = true;
return s;
}
#endregion

// #region TestFTP
// private void TestFTP()
// {
// //create an instance of the FTP class that is created.
// clsFTP ff;
//
// try
// {
// //pass values to the constructor. These values can be overridden by
setting the appropriate properties on the instance of the clsFTP class.
The
third parameter is the user name. The FTP site is accessed with the user
name. If there is no specific user name, the user name can be anonymous.
The
fourth parameter is the password. The FTP server is accessed with the
password. The fifth parameter is the port of the FTP server. The port of
the
FTP server is typically 21.
//
// ff = new clsFTP(StrIP, "/Myfolder/", "anonymous", "", 21);
//
// //try to log on to the FTP server.
// if(ff.Login() == true)
// {
// //change the directory on your FTP site.
// if(ff.ChangeDirectory("MyOwnFolder") == true)
// {
// //successful changing the directory
// ff.CreateDirectory("FTPFOLDERNEW");
// ff.ChangeDirectory("FTPFOLDERNEW");
//
// ff.SetBinaryMode(true);
//
// //upload a file from your local hard disk to the FTP site.
// ff.UploadFile("C:\Test\Example1.txt")
// ff.UploadFile("C:\Test\Example2.doc");
// ff.UploadFile("C:\Test\Example3.doc");
//
// //download a file from the FTP site to your local hard disk.
// ff.DownloadFile("Example2.doc", "C:\Test\Example2.doc");
//
// //remove a file from the FTP site.
// ff.DeleteFile("Example1.txt");
//
// //rename a file on the FTP site.
// ff.RenameFile("Example3.doc", "Example3_new.doc");
//
// //change the directory to one directory before.
// ff.ChangeDirectory("..");
// }
//
// //create a new directory.
// ff.CreateDirectory("MyOwnFolderNew");
//
// //remove the directory that is created on the FTP site.
// ff.RemoveDirectory("MyOwnFolderNew");
// }
// }
// catch(System.Exception ex)
// {
// }
// finally
// {
// //always close the connection to make sure that there are not any
not-in-use FTP connections. Check if you are logged on to the FTP server
and
then close the connection.
// if(ff.flag_bool == true)
// {
// ff.CloseConnection();
// }
// }
// }
// #endregion

}
}



--
Misbah Arefin



MDB said:
Anyone have any pointers / links / examples on how to upload files
through
FTP? I am currently using the built in file upload control however it
seems
to take a very long time to upload files and would like to explore other
ways of doing it. Any pointers or suggestions would greatly be
appreciated.
 
B

bruce barker

there is almost no difference in file transfer speed between ftp and
http (or telnet for that matter), as the transfer code is the same
(tcp/ip stream).

ftp allows multiple files, and directory options. ftp will require the
user use a ftp client, and you would need to use a ftp server (iis has
one) to recieve the files.

-- bruce (sqlwork.com)
 
M

Mark Rae [MVP]

Anyone have any pointers / links / examples on how to upload files through
FTP? I am currently using the built in file upload control however it
seems to take a very long time to upload files and would like to explore
other ways of doing it. Any pointers or suggestions would greatly be
appreciated.

If your users are uploading individual files one at a time, you're unlikely
to see very much of a speed increase with FTP...
 
M

MDB

okay thanks. Any suggestions on how to speed it up? Its take a very long
time to upload small files (2mb)?
 
R

rosoft

Are you uploading in passive or active mode? This is an essential question.

Passive Mode
The server tells the client what port to connect to.

Active Mode
THe Client tells the server what port to connect to. This raises problems
when you as a client tries to connect to a server and are behind a router
such as D-Link 604.

Is it the connection that takes time or is it the uploading of the files.
Since it happens only for smaller files I fear that it might be problem with
connecting to the server.

What software is running at the server. Do you upload to a Linux or Windows
server (or other?).

Lars

MDB said:
okay thanks. Any suggestions on how to speed it up? Its take a very long
time to upload small files (2mb)?
 
R

rosoft

Hi

There's a special tool from Dart that can handle a webservers FTP request.
ANd they have MANY more TCP tools as well. But first see if there is any FTP
server program available for Windows. It took us one year to develop our
special program when you include live testing at real clients, feedback and
bugfixing. You ship a new release and then you have to wayt a month to get
the responce just to fix a couple of lines in the code. Developing our own
tool takes time. For minor FTP activities such as uploading smaller files
like word doc for a CV ASP.NET might be sutable but for larger filer like
backups it a nother thing.

I fyou just want to upload your own files to a server you should try out the
new version of WS-FTP. That program can reconnct when a transmition is
broken. You have to tell WS-FTP when to stop trying to upload. To bad that
that program wasn't sutable for our backup project.

Yours
Lars
 
M

MDB

Its running in passive mode, also I beleive the actual uploading of the
files to the server (windows) is what is taking so long.

I think I may try out the dart.com software, just trying to figure out which
one, the powerTCP FTP for .Net or the powerWEB File Upload.



rosoft said:
Are you uploading in passive or active mode? This is an essential
question.

Passive Mode
The server tells the client what port to connect to.

Active Mode
THe Client tells the server what port to connect to. This raises problems
when you as a client tries to connect to a server and are behind a router
such as D-Link 604.

Is it the connection that takes time or is it the uploading of the files.
Since it happens only for smaller files I fear that it might be problem
with connecting to the server.

What software is running at the server. Do you upload to a Linux or
Windows server (or other?).

Lars
 
R

rosoft

Hi

I recomend that you test the upload with the excelent tool Ethereal. A
program that monitors every thing thave goes on on the network. If you have
router its even possible to track what goes on on all machines. This tool
saved me month of hard work in our backup porject. Try www.ehtereal.com and
find a download from the homepage.

Good Luck
Lars
 
J

John Talarico

rosoft --

Thanks for recommending Dart's PowerTCP products. It's always great to
see what people are building with our components.

It sounds like you are mixing web and FTP solutions, so I thought I'd
mention that we have a set of ASP.NET File Upload controls
(http://www.dart.com/pwfileup.aspx) that offer full streaming support.

This means you can upload files through a browser and immediately start
streaming data to a destination FTP server -- no need to temporarily
store files on the web app server. This works extremely well with our
FTP for .NET product, too.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,586
Members
45,096
Latest member
ThurmanCre

Latest Threads

Top