FTP CD command

L

Lou

I need to FTP to a server and give it a directory name. I never know where
the directory is
in relation to the root director so I have to do a "CD Dir"
The VB6 iNet control works like a charm but I can't for the life of me
figure out how this is done
in .NET. I scoured Google and found a ton a folks with the same issue so
this is my last hope.

VB6 iNet control code
iNet1..Execute , "CD " & myDir

works like a charm, MUST be a .NET equivalent for something so simple and
widely used....I Hope.
I did find an "Execute" method in FTP WebRequest but it doesn't except the
"CD" command as a string parameter.

-Lou
 
M

Michel Posseth [MCP]

Hello Lou here is my FTP class


<FTP CLASS >
'FTP engine met system.net.webrequest

'Michel Posseth 29-02-2008

'

Imports System.Net

Imports System.IO

Public Class FTP

Public Event eError(ByVal ex As Exception)

#Region "Properties "

Private _Uri As String

''' <summary>

''' Gets or sets the URI voor de FTP site

''' </summary>

''' <value>The URI.</value>

Public Property Uri() As String

Get

Return _Uri

End Get

Set(ByVal value As String)

_Uri = value

End Set

End Property

Private _UserName As String

''' <summary>

''' Gets or sets the name of the user.

''' </summary>

''' <value>The name of the user.</value>

Public Property UserName() As String

Get

Return _UserName

End Get

Set(ByVal value As String)

_UserName = value

End Set

End Property

Private _Password As String

''' <summary>

''' Gets or sets the password.

''' </summary>

''' <value>The password.</value>

Public Property Password() As String

Get

Return _Password

End Get

Set(ByVal value As String)

_Password = value

End Set

End Property

#End Region

#Region " Constructor "

Public Sub New(ByVal Uri As String, Optional ByVal UserName As String = "",
Optional ByVal Password As String = "")

Me.Uri = Uri

Me.UserName = UserName

Me.Password = Password

End Sub

#End Region

Public Event eDirecToryList(ByVal ListItems As String)

Public Sub List(Optional ByVal Details As Boolean = False)

List(Uri, Details)

End Sub

#Region "start stop events "

Public Event eStartFTPMethod(ByVal TaskId As String)

Public Event eStopFTPMethod(ByVal TaskId As String)

#End Region

Public Sub List(ByVal listUrl As String, Optional ByVal Details As Boolean =
False, Optional ByVal Taskid As String = "")

RaiseEvent eStartFTPMethod(Taskid)

Dim reader As StreamReader = Nothing

Try

Dim listRequest As FtpWebRequest = CType(WebRequest.Create(listUrl),
FtpWebRequest)

If String.IsNullOrEmpty(Me.UserName) Then

listRequest.Credentials = New NetworkCredential(Me.UserName, Me.Password)

End If

If Details Then

listRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails

Else

listRequest.Method = WebRequestMethods.Ftp.ListDirectory

End If

Dim listResponse As FtpWebResponse = CType(listRequest.GetResponse(),
FtpWebResponse)

reader = New StreamReader(listResponse.GetResponseStream())

RaiseEvent eDirecToryList(reader.ReadToEnd())

'Catch ex As UriFormatException

'Catch ex As WebException

Catch ex As Exception

RaiseEvent eError(ex)

Finally

If reader IsNot Nothing Then

reader.Close()

End If

RaiseEvent eStopFTPMethod(Taskid)

End Try

End Sub

''' <summary>

''' Uploads the asynch.

''' </summary>

''' <param name="fileName">Name of the file.</param>

''' <param name="uploadUrl">The upload URL.</param>

''' <param name="TaskId">The task id.</param>

Public Sub UploadAsynch(ByVal fileName As String, ByVal uploadUrl As String,
Optional ByVal TaskId As String = "")

If String.IsNullOrEmpty(TaskId) Then

TaskId = Guid.NewGuid.ToString

End If

Dim AsyncUpload As New InvokeThreeStringMeth(AddressOf Me.Upload)

AsyncUpload.BeginInvoke(fileName, uploadUrl, TaskId, Nothing, Nothing)

End Sub

''' <summary>

''' Uploads the specified file name.

''' </summary>

''' <param name="fileName">Name of the file.</param>

''' <param name="uploadUrl">The upload URL.</param>

''' <param name="TaskId">The task id.</param>

Public Sub Upload(ByVal fileName As String, ByVal uploadUrl As String,
Optional ByVal TaskId As String = "")

RaiseEvent eStartFTPMethod(TaskId)

Dim requestStream As Stream = Nothing

Dim fileStream As FileStream = Nothing

Dim uploadResponse As FtpWebResponse = Nothing

Try

Dim uploadRequest As FtpWebRequest = CType(WebRequest.Create(uploadUrl),
FtpWebRequest)

If String.IsNullOrEmpty(Me.UserName) Then

uploadRequest.Credentials = New NetworkCredential(Me.UserName, Me.Password)

End If

uploadRequest.Method = WebRequestMethods.Ftp.UploadFile

'disable eventuele proxy ( uploaden door proxy is niet ondersteund )

uploadRequest.Proxy = Nothing

requestStream = uploadRequest.GetRequestStream()

fileStream = File.Open(fileName, FileMode.Open)

Dim buffer(1024) As Byte

Dim bytesRead As Integer

While True

bytesRead = fileStream.Read(buffer, 0, buffer.Length)

If bytesRead = 0 Then

Exit While

End If

requestStream.Write(buffer, 0, bytesRead)

End While

requestStream.Close()

uploadResponse = CType(uploadRequest.GetResponse(), FtpWebResponse)

Catch ex As Exception

RaiseEvent eError(ex)

'Catch ex As UriFormatException

'

'Catch ex As IOException

'

'Catch ex As WebException

'

Finally

If uploadResponse IsNot Nothing Then

uploadResponse.Close()

End If

If fileStream IsNot Nothing Then

fileStream.Close()

End If

If requestStream IsNot Nothing Then

requestStream.Close()

End If

RaiseEvent eStopFTPMethod(TaskId)

End Try

End Sub

Delegate Sub InvokeThreeStringMeth(ByVal ParA As String, ByVal ParB As
String, ByVal ParC As String)

''' <summary>

''' Download een file asynchroon

''' </summary>

''' <param name="downloadUrl">The download URL.</param>

''' <param name="TargetLocation">The target location.</param>

''' <param name="TaskId">The task id.</param>

Public Sub DownLoadAsynch(ByVal downloadUrl As String, Optional ByVal
TargetLocation As String = "", Optional ByVal TaskId As String = "")

If String.IsNullOrEmpty(TaskId) Then

TaskId = Guid.NewGuid.ToString

End If

Dim AsyncDownLoad As New InvokeThreeStringMeth(AddressOf Me.Download)

AsyncDownLoad.BeginInvoke(downloadUrl, TargetLocation, TaskId, Nothing,
Nothing)

End Sub

''' <summary>

''' Download een file synchroon

'''

''' </summary>

''' <param name="downloadUrl">The download URL.</param>

''' <param name="TargetLocation">The target location.</param>

''' <param name="TaskId">The task id.</param>

Public Sub Download(ByVal downloadUrl As String, Optional ByVal
TargetLocation As String = "", Optional ByVal TaskId As String = "")

RaiseEvent eStartFTPMethod(TaskId)

Dim responseStream As Stream = Nothing

Dim fileStream As FileStream = Nothing

Dim reader As StreamReader = Nothing

Try

Dim downloadRequest As FtpWebRequest = _

CType(WebRequest.Create(downloadUrl), FtpWebRequest)

Dim downloadResponse As FtpWebResponse = _

CType(downloadRequest.GetResponse(), FtpWebResponse)

responseStream = downloadResponse.GetResponseStream()

Dim fileName As String = _

Path.GetFileName(downloadRequest.RequestUri.AbsolutePath)

If fileName.Length = 0 Then

reader = New StreamReader(responseStream)

Else

Dim IOPath As String = fileName

'als we geen targetpath hebben dan gaat de file naar de assembly directory

If Not String.IsNullOrEmpty(TargetLocation) AndAlso
Directory.Exists(TargetLocation) Then

IOPath = Path.Combine(TargetLocation, fileName)

End If

fileStream = File.Create(IOPath) 'als de file al bestaat wordt deze
overschreven

Dim buffer(1024) As Byte

Dim bytesRead As Integer

While True

'vul de buffer met bytes

bytesRead = responseStream.Read(buffer, 0, buffer.Length)

If bytesRead = 0 Then

'als we geen bytes meer krijgen uit de stream dan is de file compleet over

Exit While 'dus stoppen met de loop

End If

fileStream.Write(buffer, 0, bytesRead)

End While

'de finally zorgt voor het netjes afsluiten van de stream en file

End If

Catch ex As Exception

RaiseEvent eError(ex)

'Catch ex As UriFormatException

'

'Catch ex As WebException

'

'Catch ex As IOException

'

Finally

If reader IsNot Nothing Then

reader.Close()

ElseIf responseStream IsNot Nothing Then

responseStream.Close()

End If

If fileStream IsNot Nothing Then

fileStream.Close()

End If

RaiseEvent eStopFTPMethod(TaskId)

End Try

End Sub

End Class

</FTP CLASS>



And here is i test application drag and drop a new form in the ide

now drag a textbox , a button and a listbox and a folderbrowserdialog

on the form go to code view and copy paste this code

< TEST APP >

Imports System.Net

Imports System.IO

Imports ista.FTP

Public Class Form1

'' Dim Uri As String = "ftp://nl_sdm1_r23/"

Delegate Sub ParA(ByVal parA As String)

Delegate Sub ParB(ByVal parB As Exception)

Private WithEvents ftpmp As ista.FTP

Private Sub ftpmp_eDirecToryList(ByVal ListItems As String) Handles
ftpmp.eDirecToryList

Me.ListBox1.Items.Clear()

Me.ListBox1.BeginUpdate()

For Each item In ListItems.Split(CChar(vbCrLf))

If item.Trim.Length > 0 Then

Me.ListBox1.Items.Add(item)

End If

Next

Me.ListBox1.EndUpdate()

End Sub

Private Sub ftpmp_eError(ByVal ex As System.Exception) Handles ftpmp.eError

MsgBox(ex.ToString)

End Sub

Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click

Navigate()

End Sub

Private Sub Navigate()

Button1.Enabled = False

ftpmp = New ista.FTP(Me.TextBox1.Text)

ftpmp.List()

Button1.Enabled = True

End Sub

Private Sub ftpmp_eStartFTPMethod(ByVal TaskId As String) Handles
ftpmp.eStartFTPMethod

If Me.InvokeRequired Then

Dim d As New ParA(AddressOf Me.ftpmp_eStartFTPMethod)

Me.Invoke(d, New Object() {TaskId})

Else

Me.Cursor = Cursors.WaitCursor

End If

End Sub

Private Sub ftpmp_eStopFTPMethod(ByVal TaskId As String) Handles
ftpmp.eStopFTPMethod

If Me.InvokeRequired Then

Dim d As New ParA(AddressOf Me.ftpmp_eStopFTPMethod)

Me.Invoke(d, New Object() {TaskId})

Else

Me.Cursor = Cursors.Default

End If

End Sub

Private Sub ListBox1_DoubleClick(ByVal sender As Object, ByVal e As
System.EventArgs) Handles ListBox1.DoubleClick

If Not ListBox1.SelectedItem Is Nothing Then

If ListBox1.SelectedItem.ToString.Length > 1 Then

If ListBox1.SelectedItem.ToString.Contains(".") Then

'een file

If Me.FolderBrowserDialog1.ShowDialog(Me) = Windows.Forms.DialogResult.OK
AndAlso Me.FolderBrowserDialog1.SelectedPath.Length > 0 Then

ftpmp.DownLoadAsynch(Path.Combine(Me.TextBox1.Text,
ListBox1.SelectedItem.ToString.Trim), Me.FolderBrowserDialog1.SelectedPath)



End If



Else

'een subdirectory

Me.TextBox1.Text = Path.Combine(Me.TextBox1.Text,
ListBox1.SelectedItem.ToString)

Navigate()

End If

End If

End If

End Sub

End Class


</TEST APP>

note that my apps are all standard contained in the ista root namespace you
might change that to your own

for the rest it should work out of the box


ofcourse uploading is as easy as

Dim FTpUpl As New ista.FTP("ftp://nl_sdm1_r40/")

FTpUpl.Upload("C:\micheltest.txt", "ftp://nl_sdm1_r40/XMLOL/test/hallo.txt")

MsgBox("klaar")



HTH

Michel
 
L

Lou

Thanks but that code doesn't solve my problem. I have the same type of code
working but it can't handle the CD command.
Just passing the dir as the URI doesn't work. eg ftp://server/dir
I have scored the universs and no one has solved this problem. This seems to
be a problem everyone has
run into.
Let me explain.
if i conect to a FTP server using the URI i connect to some unknown
directory. I then want to send a command
to quicky go to some known directory. VB6 iNet contrrol is simple to do
this. .NET it appears impossible.
Some docs say you cann append the dir to the URI but I find that doesn't
work plus you need to know ahead of time
the structure of the directories on the server. With the iNet you simply
give it a know directory name and it just works!!!!

-Louie
 
M

Michel Posseth [MCP]

Huh ,,,,,no i don`t understand it at all

My code connects to a ftp site and the enumerates all content on that place
, if the name does not have a . it asumes this is a directory on the ftp
site if you click on it in the listview it wil go a level deeper and
enumerates all the content in that level and so on and on

So the code is capable of showing the complete directory structure on the
server and interact with it thus Download / Upload ( what more do you want
? ) , indeed i do not know a way of sending direct commands although it
might be possible with telnet.

regards

Michel
 
L

Lou

Thanks Mike but I am on my third full day of trying to get this done and I
found some stuff from MS that
says what I need to do is not implemented in the Framework(FtpWebRequest) .
From MS:::sorry.. this is not supported now. We MIGHT have a fully
functional FTP client which maintains state(instead of the stateless
webrequest response model we have now)...in the next release..
Thanks

Heres where it fails.

I ftp into a sever and connect just fine. I am in a directory that's is deep
like
server/dir/dir/dir/dir/dir
I need to explicitly go back NOT forward to the first dir then back down
another dir all with one command.
like I said the VB6 iNet control handles this with one line of code using
the CD command. Simply tell
the server to go directly to a known Directory wherever you are now.

I did see posts to pass the dir in the connect string using escape
characters etc like
("ftp://myFtpUserName:myFtpUserPassword@myFtpUrl/%2E%2E/%2E%2E

Can't get any of that to work with the server.
I realize your app works and I have one very similar but that connects, you
see a dir then can navigate etc.
What I need is the user gives a know directory name then my code need to
just go there and list all the files
in that dir.

Does this make sense
Would love to hear your thoughts and thanks for replying.

-Lou
 
M

Michel Posseth [MCP]

Lou ,

I now understand the problem , i remember to have seen a socket level FTP
client once in the time that the framework did not provide anny FTP
functionality at all , i will see if i can dig it up somewhere .

regards

Michel
 
C

Clive Lumb

Perhaps a stupid suggestion...
But, might it not be easier to make a wrapper for the ftp.exe cmd line app?
 
L

Lou

At this point NO suggestion is stupid.
-I'll look into it since no other solution works.

Thanks for the not-so-stupid suggestion.
-Lou
 
T

Tom Shelton

It's C# and it was written a long time ago :) But, it did work.
http://groups.google.com/group/micr...tp+author:tom+author:shelton#b36f43bd9b436da2

If you need async operations, then call this on a background thread or you
could with a bit of work implement the WinInet async methods...

Just realized that was a really old version! Here is one that you can
actually do a simple directory listing:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace FireAnt.Net.Ftp
{
internal static class WinInet
{
public const int INTERNET_OPEN_TYPE_PRECONFIG = 0;
public const int INTERNET_OPEN_TYPE_DIRECT = 1;
public const int INTERNET_OPEN_TYPE_PROXY = 3;
public const short INTERNET_DEFAULT_FTP_PORT = 21;
public const int INTERNET_SERVICE_FTP = 1;
public const int FTP_TRANSFER_TYPE_ASCII = 0x01;
public const int FTP_TRANSFER_TYPE_BINARY = 0x02;
public const int GENERIC_WRITE = 0x40000000;
public const int GENERIC_READ = unchecked ( (int)0x80000000 );
public const int MAX_PATH = 260;
public const int ERROR_INSUFFICIENT_BUFFER = 122;

[DllImport ( "wininet.dll", CharSet = CharSet.Auto, SetLastError = true )]
public static extern IntPtr InternetOpen (
string lpszAgent,
int dwAcessType,
string lpszProxyName,
string lpszProxyBypass,
int dwFlags );

[DllImport ( "wininet.dll", CharSet = CharSet.Auto, SetLastError = true )]
public static extern IntPtr InternetConnect (
IntPtr hInternet,
string lpszServerName,
short nServerPort,
string lpszUserName,
string lpszPassword,
int dwService,
int dwFlags,
ref int dwContext );

[DllImport ( "wininet.dll", CharSet = CharSet.Auto, SetLastError = true )]
public static extern bool FtpGetCurrentDirectory (
IntPtr hConnect,
StringBuilder lpszCurrentDirectory,
ref int lpdwCurrentDirectory );

[DllImport ( "wininet.dll", CharSet = CharSet.Auto, SetLastError = true )]
public static extern bool FtpSetCurrentDirectory (
IntPtr hConnect,
string lpszCurrentDirectory );

[DllImport ( "wininet.dll", CharSet = CharSet.Auto, SetLastError = true )]
public static extern IntPtr FtpOpenFile (
IntPtr hConnect,
string lpszFileName,
int dwAccess,
int dwFlags,
out int dwContext );

[DllImport ( "wininet.dll", SetLastError = true )]
public static extern bool InternetWriteFile (
IntPtr hFile,
[MarshalAs ( UnmanagedType.LPArray )] byte[] lpBuffer,
int dwNumberOfBytesToWrite,
out int lpdwNumberOfBytesWritten );

[DllImport ( "wininet.dll", SetLastError = true )]
public static extern bool InternetReadFile (
IntPtr hFile,
[MarshalAs ( UnmanagedType.LPArray )] byte[] lpBuffer,
int dwNumberOfBytesToRead,
out int lpdwNumberOfBytesRead
);

[DllImport ( "wininet.dll", CharSet = CharSet.Auto, SetLastError = true )]
public static extern bool InternetCloseHandle ( IntPtr hInternet );

[DllImport ( "wininet.dll", CharSet = CharSet.Auto, SetLastError = true )]
public static extern bool FtpPutFile (
IntPtr hConnect,
string lpszLocalFile,
string lpszNewRemoteFile,
int dwFlags,
out int dwContext );

[DllImport ( "wininet.dll", CharSet = CharSet.Auto, SetLastError = true )]
public static extern bool FtpGetFile (
IntPtr hConnect,
string lpszRemoteFile,
string lpszLocalFile,
bool failIfExists,
int dwFlagsAttributes,
int dwFlags,
out int dwContext );

[DllImport ( "wininet.dll", CharSet = CharSet.Auto, SetLastError = true )]
public static extern bool FtpCreateDirectory (
IntPtr hConnect,
string lpszDirectory );

// BOOL FtpCommand(
// __in HINTERNET hConnect,
// __in BOOL fExpectResponse,
// __in DWORD dwFlags,
// __in LPCTSTR lpszCommand,
// __in DWORD_PTR dwContext,
// __out HINTERNET *phFtpCommand
//);

[DllImport ( "wininet.dll", CharSet = CharSet.Auto, SetLastError = true )]
public static extern IntPtr FtpFindFirstFile (
IntPtr hConnect,
string lpszSearchFile,
out WIN32_FIND_DATA lpFindFileData,
uint dwFlags,
out int dwContext );

[DllImport("wininet.dll", CharSet=CharSet.Auto, SetLastError=true)]
public static extern bool InternetFindNextFile (
IntPtr hFind,
out WIN32_FIND_DATA lpvFindData);

[DllImport ( "wininet.dll", CharSet = CharSet.Auto, SetLastError = true )]
public static extern bool InternetGetLastResponseInfo (
out int lpdwError,
StringBuilder lpszBuffer,
ref int lpdwBufferLength );

[StructLayout(LayoutKind.Sequential)]
public struct FILETIME
{
public uint dwLowDateTime;
public uint dwHighDateTime;

}

[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)]
public struct WIN32_FIND_DATA
{
public uint dwFileAttributes;
public FILETIME ftCreationTime;
public FILETIME ftLastAccessTime;
public FILETIME ftLastWriteTime;
public uint nFileSizeHigh;
public uint nFileSizeLow;
public uint dwReserved0;
public uint dwReserved1;

[MarshalAs ( UnmanagedType.ByValTStr, SizeConst = MAX_PATH )]
public string cFileName;
[MarshalAs ( UnmanagedType.ByValTStr, SizeConst = 14 )]
public string cAlternateFileName;
}
}

}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.IO;

namespace FireAnt.Net.Ftp
{
[Flags ()]
public enum AccessMode
{
Read = WinInet.GENERIC_READ,
Write = WinInet.GENERIC_WRITE,
}

public enum TransferMode
{
Ascii = WinInet.FTP_TRANSFER_TYPE_ASCII,
Binary = WinInet.FTP_TRANSFER_TYPE_BINARY,
}

public class FtpFileInfo
{
internal FtpFileInfo ( WinInet.WIN32_FIND_DATA info )
{
this.Name = info.cFileName;
this.IsDirectory = Convert.ToBoolean ( info.dwFileAttributes & 0x10 );
}

public string Name { get; internal set; }
public bool IsDirectory { get; internal set; }
}

/// <summary>
/// Summary description for SimpleFTP.
/// </summary>
public sealed class SimpleFtp : IDisposable
{
private IntPtr internet;
private IntPtr connection;
private IntPtr fileHandle;
private int context;

private const int BUFFER_SIZE = 2048;

public SimpleFtp ( string host, string userName, string password )
{
internet = WinInet.InternetOpen (
null,
WinInet.INTERNET_OPEN_TYPE_DIRECT,
null,
null,
0 );

if ( internet == IntPtr.Zero )
{
throw new Win32Exception ( Marshal.GetLastWin32Error () );
}

connection = WinInet.InternetConnect (
this.internet,
host,
WinInet.INTERNET_DEFAULT_FTP_PORT,
userName,
password,
WinInet.INTERNET_SERVICE_FTP,
0,
ref this.context );

if ( connection == IntPtr.Zero )
{
WinInet.InternetCloseHandle ( this.internet );
throw new Win32Exception ( Marshal.GetLastWin32Error () );
}
}

~SimpleFtp ()
{
this.CleanUp ();
}

void IDisposable.Dispose ()
{
this.CleanUp ();
GC.SuppressFinalize ( this );
}

public string CurrentDirectory
{
get
{
StringBuilder path = new StringBuilder ( 260 );
int bufferSize = path.Capacity;

if ( !WinInet.FtpGetCurrentDirectory ( this.connection, path, ref bufferSize ) )
{
throw new Win32Exception ( Marshal.GetLastWin32Error () );
}
return path.ToString ();
}
set
{
if ( !WinInet.FtpSetCurrentDirectory ( this.connection, value ) )
{
throw new Win32Exception ( Marshal.GetLastWin32Error () );
}
}
}

public void Close ()
{
( (IDisposable)this ).Dispose ();
}

public void OpenFile ( string fileName, AccessMode access, TransferMode mode )
{
this.fileHandle = WinInet.FtpOpenFile ( this.connection, fileName, (int)access, (int)mode, out this.context );
if ( this.fileHandle == IntPtr.Zero )
{
throw new Win32Exception ( Marshal.GetLastWin32Error () );
}
}

public void CloseFile ()
{
if ( this.fileHandle != IntPtr.Zero )
{
if ( WinInet.InternetCloseHandle ( this.fileHandle ) )
{
this.fileHandle = IntPtr.Zero;
}
else
{
throw new Win32Exception ( Marshal.GetLastWin32Error () );
}
}
}

public int WriteFile ( string buffer )
{
byte[] bytes = new ASCIIEncoding ().GetBytes ( buffer );
return this.WriteFile ( bytes );
}

public int WriteFile ( byte[] buffer )
{
int byteCount;
if ( !WinInet.InternetWriteFile ( this.fileHandle, buffer, buffer.Length, out byteCount ) )
{
throw new Win32Exception ( Marshal.GetLastWin32Error () );
}
return byteCount;
}

public bool ReadFile ( out string buffer )
{
// clear the buffer...
buffer = string.Empty;

// read from the file
int bytesRead;
byte[] readBuffer = new byte[SimpleFtp.BUFFER_SIZE];
bool success = WinInet.InternetReadFile ( this.fileHandle, readBuffer, readBuffer.Length, out bytesRead );

// the call failed!
if ( !success )
{
throw new Win32Exception ( Marshal.GetLastWin32Error () );
}

// we got some data, so convert it for the return...
if ( bytesRead != 0 )
{
buffer = Encoding.ASCII.GetString ( readBuffer, 0, bytesRead );
}

return ( bytesRead != 0 ) ? true : false;
}

public bool ReadFile ( byte[] buffer )
{
int bytesRead;
bool success = WinInet.InternetReadFile ( this.fileHandle, buffer, buffer.Length, out bytesRead );
if ( !success )
{
throw new Win32Exception ( Marshal.GetLastWin32Error () );
}
return ( bytesRead != 0 ) ? true : false;
}

public void GetFile ( string localFile, string remoteFile, bool fail )
{
GetFile ( localFile, remoteFile, TransferMode.Ascii, fail );
}

public void GetFile ( string localFile, string remoteFile, TransferMode mode, bool fail )
{
if ( !WinInet.FtpGetFile ( connection, remoteFile, localFile, fail, 0, (int)mode, out context ) )
{
int errorCode = Marshal.GetLastWin32Error ();
if ( errorCode == 12003 )
{
int realError;
int capacity = 1024;
StringBuilder buffer = new StringBuilder ( capacity );

while ( !WinInet.InternetGetLastResponseInfo ( out realError, buffer, ref capacity ) )
{
if ( Marshal.GetLastWin32Error () == WinInet.ERROR_INSUFFICIENT_BUFFER )
{
buffer = new StringBuilder ( ++capacity );
}
else
{
throw new Exception ( "Unable to retrieve extended error information." );
}
}

throw new Win32Exception ( realError, buffer.ToString () );
}
else
{
throw new Win32Exception ( Marshal.GetLastWin32Error () );
}
}
}

public void CreateDirectory ( string remoteDir )
{
if ( !WinInet.FtpCreateDirectory ( connection, remoteDir ) )
{
throw new Win32Exception ( Marshal.GetLastWin32Error () );
}
}

public void PutFile ( string localFile, string remoteFile )
{
this.PutFile ( localFile, remoteFile, TransferMode.Ascii );
}

public void PutFile ( string localFile, string remoteFile, TransferMode mode )
{
if ( !WinInet.FtpPutFile ( this.connection, localFile, remoteFile, (int)mode, out this.context ) )
{
throw new Win32Exception ( Marshal.GetLastWin32Error () );
}
}

public FtpFileInfo[] Dir (string mask)
{
List<FtpFileInfo> files = new List<FtpFileInfo> ();
WinInet.WIN32_FIND_DATA data;
IntPtr hFind = WinInet.FtpFindFirstFile ( this.connection, null, out data, 0, out this.context );
if ( hFind != IntPtr.Zero )
{
files.Add( new FtpFileInfo(data) );
while ( WinInet.InternetFindNextFile ( hFind, out data ) )
{
files.Add( new FtpFileInfo(data) );
}
}
WinInet.InternetCloseHandle ( hFind );
return files.ToArray ();
}

private void CleanUp ()
{
if ( this.fileHandle != IntPtr.Zero )
{
WinInet.InternetCloseHandle ( this.fileHandle );
}

if ( this.connection != IntPtr.Zero )
{
WinInet.InternetCloseHandle ( this.connection );
}

if ( this.internet != IntPtr.Zero )
{
WinInet.InternetCloseHandle ( this.internet );
}
}
}
}


Simple example of use after compiling to a class library:
Using ftp As New SimpleFtp(myhost, myuser, mypassword)
Console.WriteLine (ftp.CurrentDirectory)
For Each info In ftp.Dir(String.Empty)
Console.WriteLine("{0}, IsDirectory={1}", info.Name, info.IsDirectory)
Next
End Using
 
L

Lou

Got it working using batch files and calling them from .NET.
Boy is this clunky. How did .NET drop the ball on FTP?
A simple CD command would have helped!!!! Arggggg
Many lost development days......

-Lou
 
J

J. Moreno

Lou said:
Got it working using batch files and calling them from .NET.
Boy is this clunky. How did .NET drop the ball on FTP?
A simple CD command would have helped!!!! Arggggg
Many lost development days......

They didn't. FTPWebRequest is a lightweight tool intended for simple
things. If you need something that more (in particular something with a
steady connection) then you need to use something else.

And MS provides, see...

ms-help://MS.VSCC.v80/MS.MSDN.v80/MS.KB.v10.en/enu_kbvbnetkb/vbnetkb/832679.htm

(You have to have the right version of the MSDN library installed to see
it).

Anyway, the above help article contains a clsFTP that should meet your
needs (if you don't have the right MSDN library installed, google for
"m_iremoteport m_ibytes").
 
M

Michel Posseth [MCP]

Hello Lou,



wel it was a big search in my code library ,,,, but ..... here it is

Imports System.IO
Imports System.Net.Sockets
Imports System.Text
Imports System.Threading
Imports System.Security
Imports System.Management

Module FTP

Enum TransferMode
Ascii
Binary
End Enum

Public Class FtpClient
Const BUFFSIZE As Integer = 4096
Private strErrorCode As String = ""
Private strErrorMessage As String = ""
Private bConnectionOpen As Boolean = False
Private m_LogFileDirectory As String = "C:\"
Private m_sUsername As String = ""
Private m_sPassword As String = ""
Private m_sHost As String = ""
Private m_iPort As Integer = 21
Private m_tcpClient As TcpClient
Private m_commandStream As NetworkStream
Dim intFTPLog As Integer = FreeFile()

Private Sub SendFTPCommand(ByVal command As String)
If command.Length > 4 AndAlso command.Substring(0, 4) = "PASS"
Then
WriteToFTPLog("PASS")
Else
WriteToFTPLog(command)
End If
Try
m_commandStream.Write(System.Text.Encoding.ASCII.GetBytes(command
& vbCrLf), 0, command.Length + 2)
Catch EX As Exception
Throw New FtpClientException(0, "SendFTPCommand" & vbCrLf &
EX.Message)
End Try
End Sub

Friend Sub FtpClient(ByVal sHost As String, ByVal sUser As String,
ByVal sPassword As String)
m_sHost = sHost
m_sUsername = sUser
m_sPassword = sPassword
End Sub
#If False Then
Friend Sub FtpClient(ByVal sHost As String)
m_sHost = sHost
End Sub

Public Sub FtpClient(ByVal sHost As String, ByVal iPort As Integer)
m_sHost = sHost
m_iPort = iPort
End Sub
#End If
Friend Property Username() As String
Get
Return m_sUsername
End Get
Set(ByVal Value As String)
m_sUsername = Value
End Set
End Property

Friend Property Password() As String
Get
Return m_sPassword
End Get
Set(ByVal Value As String)
m_sPassword = Value
End Set
End Property

Friend Property Host() As String
Get
Return m_sHost
End Get
Set(ByVal Value As String)
m_sHost = Value
End Set
End Property

Friend Property Port() As Integer
Get
Return m_iPort
End Get
Set(ByVal Value As Integer)
m_iPort = Value
End Set
End Property

Friend Property LogFileDirectory() As String
Get
Return m_LogFileDirectory
End Get
Set(ByVal Value As String)
m_LogFileDirectory = Value
If Not m_LogFileDirectory.EndsWith("\") Then
m_LogFileDirectory += "\"
End If
End Set
End Property

Friend Sub Open()
Dim sOut As String = ""
'
' FTP Log File
'
Dim strLogFile As String = m_LogFileDirectory &
Application.ProductName & "_FTP.LOG"
If File.Exists(strLogFile) AndAlso
File.GetLastWriteTime(strLogFile).Date = Now.Date Then
Try
' Open file for logging.
FileOpen(intFTPLog, strLogFile, OpenMode.Append,
OpenAccess.Write, OpenShare.LockWrite)
Catch MyException As System.Exception
Throw New FtpClientException(0, _
String.Concat("Unable to create ", strLogFile, _
vbNewLine, _
MyException.Message))
End Try
Else
Try
' Open file for logging.
FileOpen(intFTPLog, strLogFile, OpenMode.Output,
OpenAccess.Write, OpenShare.LockWrite)
Catch MyException As System.Exception
Throw New FtpClientException(0, _
String.Concat("Unable to create ", strLogFile, _
vbNewLine, _
MyException.Message))
End Try
End If
'
'
'
If (bConnectionOpen) Then
Throw New FtpClientException(0, "Open" & vbCrLf & "FTP
Connection already open")
End If

Try
m_tcpClient = New TcpClient
WriteToFTPLog("FTP " & m_sHost)
m_tcpClient.SendTimeout = 5000
m_tcpClient.ReceiveTimeout = 5000
m_tcpClient.Connect(m_sHost, m_iPort)
m_tcpClient.ReceiveBufferSize = 4096 ' allocate a 4kb buffer
m_tcpClient.SendBufferSize = 4096
m_tcpClient.NoDelay = True
Catch e As SocketException
Throw New FtpClientException(e.ErrorCode, _
"Open" & vbCrLf & _
"TCPClient cannot establish a connection to " & m_sHost
& " on Port " & m_iPort.ToString & vbCrLf & _
e.Message)
End Try
m_commandStream = m_tcpClient.GetStream ' Get the command stream
' We just successfully connected so the server welcomes us with
a 220 response
sOut = ReadReply(True)
If Not ReplyContains("220", sOut, strErrorCode, strErrorMessage)
Then
Throw New FtpClientException(CInt(strErrorCode), "Open" &
vbCrLf & strErrorMessage)
End If

SendFTPCommand("USER " & m_sUsername) ' send our user name
' the server must reply with 331
sOut = ReadReply()
If Not ReplyContains("331", sOut, strErrorCode, strErrorMessage)
Then
Throw New FtpClientException(CInt(strErrorCode), "User" &
vbCrLf & strErrorMessage)
End If

SendFTPCommand("PASS " & m_sPassword) ' send our password
sOut = ReadReply(True)
If Not ReplyContains("230", sOut, strErrorCode, strErrorMessage)
Then
Throw New FtpClientException(CInt(strErrorCode), "Password"
& vbCrLf & strErrorMessage)
End If
bConnectionOpen = True
End Sub

Friend Sub SetCurrentDirectory(ByVal sDirectory As String)
If (Not bConnectionOpen) Then
Throw New FtpClientException(0, "SetCurrentDirectory" &
vbCrLf & "Connection not open")
End If
SendFTPCommand("CWD " & sDirectory) ' send the command to change
directory
Dim sOut As String = ReadReply()
' FTP server must reply with 250, else the directory does not
exist
If Not ReplyContains("250", sOut, strErrorCode, strErrorMessage)
Then
Throw New FtpClientException(CInt(strErrorCode),
strErrorMessage)
End If
End Sub

Friend Sub ReceiveFile( _
ByVal sLocalFilename As String, _
ByVal sRemoteFilename As String, _
ByVal XferMode As TransferMode)

Dim objLocalFileStream As FileStream
Dim mTCPData As New TcpClient
Dim mDataStream As NetworkStream
Dim Port As Integer = 20
Dim strIPAddress As String
Dim sOut As String = ""

If (Not bConnectionOpen) Then
Throw New FtpClientException(0, "ReceiveFile" & vbCrLf &
"Connection not open")
End If
Try
objLocalFileStream = New FileStream(sLocalFilename,
FileMode.Create, FileAccess.ReadWrite, FileShare.Read, BUFFSIZE, False)
Catch ex As FileNotFoundException
Throw New FtpClientException(0, "Open Local File - File Not
Found" & vbCrLf & sLocalFilename & vbCrLf & ex.Message)
Catch ex As DirectoryNotFoundException
Throw New FtpClientException(0, "Open Local File - Directory
Not Found" & vbCrLf & sLocalFilename & vbCrLf & ex.Message)
Catch ex As SecurityException
Throw New FtpClientException(0, "Open Local File" & vbCrLf &
sLocalFilename & vbCrLf & ex.Message)
Catch ex As UnauthorizedAccessException
Throw New FtpClientException(0, "Open Local File" & vbCrLf &
sLocalFilename & vbCrLf & ex.Message)
Catch ex As Exception
Throw New FtpClientException(0, "Open Local File" & vbCrLf &
sLocalFilename & vbCrLf & ex.Message)
End Try
' Set transfer mode
Select Case XferMode
Case TransferMode.Ascii
SendFTPCommand("TYPE A")
sOut = ReadReply()
Case TransferMode.Binary
SendFTPCommand("TYPE I")
sOut = ReadReply()
End Select
Application.DoEvents()
'
'
Call ReadyDataSocketAndSendCommand("RETR " &
Path.GetFileName(sLocalFilename), _
"ReceiveFile", mTCPData, mDataStream)
Dim bData(1024) As Byte
Dim bytesRead As Integer = 0
' Retrieve the file
bytesRead = mDataStream.Read(bData, 0, BUFFSIZE)
Do While (bytesRead > 0)
objLocalFileStream.Write(bData, 0, bytesRead)
bytesRead = mDataStream.Read(bData, 0, BUFFSIZE)
Application.DoEvents()
Loop
objLocalFileStream.Close()
objLocalFileStream = Nothing
mDataStream.Close()
mDataStream = Nothing
mTCPData.Close()
mTCPData = Nothing
Thread.Sleep(200)
sOut = ReadReply()
End Sub

Friend Sub SendFile( _
ByVal sLocalFilename As String, _
ByVal sRemoteFilename As String, _
ByVal XferMode As TransferMode)
Dim objLocalFileStream As FileStream
Dim mTCPData As New TcpClient
Dim mDataStream As NetworkStream
Dim Port As Integer = 20
Dim strIPAddress As String
Dim sOut As String = ""
If (Not bConnectionOpen) Then
Throw New FtpClientException(0, "SendFile" & vbCrLf &
"Connection not open")
End If
Try
objLocalFileStream = New FileStream(sLocalFilename,
FileMode.Open, FileAccess.Read, FileShare.Read, BUFFSIZE, False)
Catch ex As FileNotFoundException
Throw New FtpClientException(0, "Open Local File" & vbCrLf &
sLocalFilename & vbCrLf & ex.Message)
Catch ex As DirectoryNotFoundException
Throw New FtpClientException(0, "Open Local File" & vbCrLf &
sLocalFilename & vbCrLf & ex.Message)
Catch ex As SecurityException
Throw New FtpClientException(0, "Open Local File" & vbCrLf &
sLocalFilename & vbCrLf & ex.Message)
Catch ex As UnauthorizedAccessException
Throw New FtpClientException(0, "Open Local File" & vbCrLf &
sLocalFilename & vbCrLf & ex.Message)
Catch ex As Exception
Throw New FtpClientException(0, "Open Local File" & vbCrLf &
sLocalFilename & vbCrLf & ex.Message)
End Try
' Set transfer mode
Select Case XferMode
Case TransferMode.Ascii
SendFTPCommand("TYPE A")
sOut = ReadReply()
Case TransferMode.Binary
SendFTPCommand("TYPE I")
sOut = ReadReply()
End Select
Application.DoEvents()

Call ReadyDataSocketAndSendCommand("STOR " &
Path.GetFileName(sLocalFilename), _
"SendFile", mTCPData, mDataStream)

Dim bData(BUFFSIZE) As Byte
Dim bytesRead As Integer = 0
' Upload the file
bytesRead = objLocalFileStream.Read(bData, 0, BUFFSIZE)
Do While (bytesRead > 0)
mDataStream.Write(bData, 0, bytesRead)
bytesRead = objLocalFileStream.Read(bData, 0, BUFFSIZE)
Application.DoEvents()
Loop
objLocalFileStream.Close()
objLocalFileStream = Nothing
mDataStream.Close()
mDataStream = Nothing
mTCPData.Close()
mTCPData = Nothing
Thread.Sleep(200)
sOut = ReadReply()
End Sub

Friend Sub CloseConnection()
Dim sOut As String = ""
If bConnectionOpen Then
bConnectionOpen = False
SendFTPCommand("QUIT")
sOut = ReadReply()
If Not ReplyContains("221", sOut, strErrorCode,
strErrorMessage) Then
FileClose(intFTPLog)
Throw New FtpClientException(CInt(strErrorCode),
strErrorMessage)
End If
End If
FileClose(intFTPLog)
End Sub

Friend Function GetFileList(ByVal mask As String) As Collection
Dim mTCPData As New TcpClient
Dim mDataStream As NetworkStream
Dim Port As Integer = 20
Dim strIPAddress As String
Dim sOut As String = ""

Dim ASCII As Encoding = Encoding.ASCII
'
Call ReadyDataSocketAndSendCommand("NLST " & mask, _
"GetFileList", mTCPData, mDataStream)
Dim bData(BUFFSIZE) As Byte
Dim bytesRead As Integer = 0
Dim strFileNames As String = ""
' Retrieve the directory listing
bytesRead = mDataStream.Read(bData, 0, BUFFSIZE)
Do While (bytesRead > 0)
strFileNames += ASCII.GetString(bData, 0, bytesRead)
bytesRead = mDataStream.Read(bData, 0, BUFFSIZE)
Application.DoEvents()
Loop
mDataStream.Close()
mDataStream = Nothing
mTCPData.Close()
mTCPData = Nothing
Thread.Sleep(200)
sOut = ReadReply()
'
' Move from String to Collection
'
Dim x As Integer = 0
Dim y As Integer = 0
GetFileList = New Collection
While x < strFileNames.Length
y = strFileNames.IndexOf(CChar(vbCr), x)
GetFileList.Add(strFileNames.Substring(x, y - x))
Debug.WriteLine( _
GetFileList.Count.ToString & " " & _
strFileNames.Substring(x, y - x) & _
" Length=" & strFileNames.Substring(x, y -
x).Length.ToString)
x = y + 2
End While

End Function

Private Function ReadReply(Optional ByVal bMultiLine As Boolean =
False) As String
Dim strCompleteMessage As String = ""
Dim strLastRecordRead As String = ""
Dim tmStart As Date = Now
Do
Application.DoEvents()
If m_commandStream.CanRead Then
Dim myReadBuffer(1024) As Byte
Dim numberOfBytesRead As Integer = 0
Do
Application.DoEvents()
Try
numberOfBytesRead = 0
If m_commandStream.DataAvailable Then
numberOfBytesRead =
m_commandStream.Read(myReadBuffer, 0, myReadBuffer.Length)
End If
Catch ex As Exception
Debug.WriteLine("m_commandStream.Read: " &
ex.Message)
Throw New FtpClientException(0, "ReadReply" &
vbCrLf & ex.Message)
End Try
If numberOfBytesRead > 0 Then
strLastRecordRead =
Encoding.ASCII.GetString(myReadBuffer, 0, numberOfBytesRead)
Debug.Write(Format(Now, "HH:mm:ss.ffff") & " FTP
Response: " & strLastRecordRead)
WriteToFTPLog(strLastRecordRead)
strCompleteMessage =
String.Concat(strCompleteMessage, strLastRecordRead)
End If
Loop While m_commandStream.DataAvailable
End If
Loop Until DateDiff(DateInterval.Second, tmStart, Now) > 5 Or _
(Not bMultiLine AndAlso _
strLastRecordRead.Length > 2 AndAlso
IsNumeric(strLastRecordRead.Substring(0, 3)))
If strCompleteMessage.Length = 0 Then
strCompleteMessage = "No response received"
End If
ReadReply = strCompleteMessage
End Function

Private Function ReplyContains(ByVal strCode As String, ByVal sOut
As String, _
ByRef strErrorCode As String, ByRef strErrorMessage As String)
As Boolean
ReplyContains = sOut.IndexOf(strCode) > -1
strErrorMessage = ""
strErrorCode = "0"
If sOut.Length > 3 AndAlso IsNumeric(sOut.Substring(0, 3)) Then
strErrorCode = sOut.Substring(0, 3)
strErrorMessage = sOut.Substring(3).Trim
End If
End Function

Private Sub ParsePASVResult(ByVal sOut As String, ByRef strIPAddress
As String, ByRef intPortNumber As Integer)
Dim arTokens() As String
Dim x As Integer
Dim y As Integer
Try
x = sOut.IndexOf("(")
y = sOut.IndexOf(")", x)
arTokens = sOut.Substring(x + 1, y - x -
1).Split(CChar(","))
strIPAddress = String.Concat(arTokens(0), ".", arTokens(1),
".", arTokens(2), ".", arTokens(3))
intPortNumber = (CInt(arTokens(4)) * 256) +
CInt(arTokens(5))
Catch ex As Exception
Throw New FtpClientException(0, "Malformed PASV result." &
vbCrLf & ex.Message)
End Try
End Sub

Private Sub WriteToFTPLog(ByVal strMessage As String)
Print(intFTPLog, Format(Now, "MM/dd/yyyy HH:mm:ss.ffff") & " " &
_
strMessage & DirectCast(IIf(strMessage.EndsWith(vbCrLf), "",
vbCrLf), String))
End Sub

Sub ReadyDataSocketAndSendCommand(ByVal strCommand As String, _
ByVal strMethodName As String, _
ByRef mTCPData As TcpClient, _
ByRef mDataStream As NetworkStream)
Dim sOut As String
Dim strIPAddress As String

If (Not bConnectionOpen) Then
Throw New FtpClientException(0, strMethodName & vbCrLf &
"Connection not open")
End If
'
' Set Passive Mode
'
' Passive mode opens the connection on the remote computer and
returns
' a port number to use. Later, this causes message 125. No
worries!
' That's what is supposed to happen.
'
SendFTPCommand("PASV")
sOut = ReadReply()
If Not ReplyContains("227", sOut, strErrorCode, strErrorMessage)
Then
Throw New FtpClientException(CInt(strErrorCode), "PASV" &
vbCrLf & strErrorMessage)
End If
ParsePASVResult(sOut, strIPAddress, Port)
Application.DoEvents()
'
' Open a socket
'
Try
mTCPData = New TcpClient(strIPAddress, Port)
Catch ex As Exception
Throw New FtpClientException(0, "Open Socket" & vbCrLf & _
strIPAddress & " " & Port.ToString & vbCrLf &
ex.Message)
End Try
mTCPData.ReceiveBufferSize = BUFFSIZE
mTCPData.SendBufferSize = BUFFSIZE
Try
mDataStream = mTCPData.GetStream()
Catch ex As Exception
Throw New FtpClientException(0, "GetStream" & vbCrLf & _
strIPAddress & " " & Port.ToString & vbCrLf &
ex.Message)
End Try
' Send the FTP Command to the FTP Server
SendFTPCommand(strCommand)
sOut = ReadReply()
' We will get either a confirmation of the download or an error
message
If Not ReplyContains("150", sOut, strErrorCode, strErrorMessage)
AndAlso _
Not ReplyContains("125", sOut, strErrorCode,
strErrorMessage) Then
Throw New FtpClientException(CInt(strErrorCode), strCommand
& vbCrLf & strErrorMessage)
End If
End Sub

Protected Overrides Sub Finalize()
If bConnectionOpen Then
Call CloseConnection()
End If
End Sub
End Class

Friend Class FtpClientException
Inherits Exception
Dim m_iErrorCode As Integer = 0
Dim m_ErrorMessage As String = ""
Friend Sub New(ByVal code As Integer, ByVal message As String)
m_iErrorCode = code
m_ErrorMessage = message
Throw Me
End Sub
Friend ReadOnly Property ErrorCode() As Integer
Get
Return m_iErrorCode
End Get
End Property
Friend ReadOnly Property ErrorMessage() As String
Get
Return m_ErrorMessage
End Get
End Property
End Class

#If False Then
Function CheckDiskDrive(ByVal strFileTitle As String) As String
Try
Dim d As String = strFileTitle.Substring(0, 2).ToUpper
CheckDiskDrive = ""
If d.Substring(1, 1) = ":" Then
Dim searcher As New ManagementObjectSearcher( _
"SELECT * FROM Win32_LogicalDisk Where Name=" & Chr(34)
& d & Chr(34))
If searcher.Get.Count > 0 Then
Dim share As ManagementObject
For Each share In searcher.Get
Dim decFreespace As Decimal =
System.Convert.ToDecimal(DirectCast(share("FreeSpace"), UInt64)) / (1024 *
1024)
Dim s As String = "=" &
share("Name").ToString.ToUpper
If s.Substring(1) = d Then
s = ""
End If
CheckDiskDrive = d & s & vbNewLine & _
Format(decFreespace,
"###,###,###,###,###,###,###") & "MB Free Disk Space" & vbNewLine & _
DirectCast(IIf(decFreespace < 5, "WARNING:
Severe shortage of disk space", ""), String)
Next share
End If
End If
Catch ex As Exception
CheckDiskDrive = ""
End Try
End Function
#End If
End Module


Regards

Michel Posseth





Lou said:
When I log on to my FTP server I cannot have it go to a know directory.
It always returns a 550. I must have viewd 1000 Google pages and found no
solution.
WHY ISN"T THERE A "CD" WEBREQUEST METHOD!!!!!!!!!!!!!!!!

When I log in and do a PWD I get back
Dir1\dir2\dir3\dir4\dir5

I need to log in and have it go back up four dirs

Dim ftpReq As FtpWebRequest = WebRequest.Create(ftp://MyServer/Dir1//)

I have tried all these variations as well

Dim ftpReq As FtpWebRequest = WebRequest.Create(ftp://MyServer/%2fDir1//)

Dim ftpReq As FtpWebRequest = WebRequest.Create(ftp://MyServer//Dir1//)



-Lou
 

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

Similar Threads


Top