Open "C:\log.txt" For Append As #1
Print#1, "Привет"
Close#1
Вот этот код для открытия и сохранения текста в файл на компе....а как сделать то же самое но если файл находится на сервере?? Заранее большое спасибо
Option Explicit
'**************************************
' Имя: FtpPutFile
' Описание : Сохранение файла на FTP сервере
' Автор: Robert N.
' Автор частичного русского перевода: SCINER (lenar2003@mail.ru)
'
' Вводные данные:
' hConnect — Валидный HINTERNET хендл FTP сессии.
' с — Адрес завершающийся нулевым символом(null-terminated String), значение содержит имя файла отправляемого с локального диска.
' lpszNewRemoteFile — Адрес завершающийся нулевым символом(null-terminated String), значение содержит имя файла содаваемого на FTP сервере.
' dwFlags — Unsigned Long Integer value that contains the conditions under which the transfers occur. The application should Select one transfer Type and any of the flags that control how the caching of the file will be controlled.
'Метод передачи может принимать любое из перечисленных ниже значений:
' FTP_TRANSFER_TYPE_ASCII — Передает файл используя режим передачи FTP's ASCII (Тип A). Control and formatting information is converted To local equivalents.
' FTP_TRANSFER_TYPE_BINARY — ередает файл используя режим передачи FTP's Изображение(Image) (Тип I). The file is transferred exactly as it exists With no changes. This is the default transfer method.
' FTP_TRANSFER_TYPE_UNKNOWN — Метод по умолчанию FTP_TRANSFER_TYPE_BINARY.
' INTERNET_FLAG_TRANSFER_ASCII — Передает файл как ASCII.
' INTERNET_FLAG_TRANSFER_BINARY — Передает файл как двоичный(binary).
'
'The following values are used To control the caching of the file.
'The application can use one or more of the following values:
'INTERNET_FLAG_HYPERLINK
'
'Forces a reload If there was no Expires time and no LastModified time returned from the server when determining whether To reload the item from the network.
' INTERNET_FLAG_NEED_FILE
' Causes a temporary file To be created If the file cannot be cached.
' INTERNET_FLAG_RELOAD
'
' Forces a download of the requested file, object, or directory listing from the origin server, Not from the cache.
' INTERNET_FLAG_RESYNCHRONIZE
' Reloads HTTP resources If the resource has been modified since the last time it was downloaded. All FTP and Gopher resources are reloaded.
' · dwContext
' [in] Address of an unsigned Long Integer value that contains the application-defined value that associates this search With any application data. This parameter is used only If the application has a
'
' Returns: Returns TRUE if successful, or FALSE otherwise. To get a specific error code, call GetLastError.
'
'This code is copyrighted and has' limited warranties.
'Оригинальная версия расположена по адресу http://www.Planet-Source-Code.com/vb/scripts/ShowCode.asp?txtCodeId=39927&lngWId=1'for details.
'**************************************
Const FTP_TRANSFER_TYPE_UNKNOWN = &H0
Const FTP_TRANSFER_TYPE_ASCII = &H1
Const FTP_TRANSFER_TYPE_BINARY = &H2
Const INTERNET_DEFAULT_FTP_PORT = 21 ' default For FTP servers
Const INTERNET_SERVICE_FTP = 1
Const INTERNET_FLAG_PASSIVE = &H8000000 ' used For FTP connections
Const INTERNET_OPEN_TYPE_PRECONFIG = 0 ' use registry configuration
Const INTERNET_OPEN_TYPE_DIRECT = 1 ' direct To net
Const INTERNET_OPEN_TYPE_PROXY = 3 ' via named proxy
Const INTERNET_OPEN_TYPE_PRECONFIG_WITH_NO_AUTOPROXY = 4 ' prevent using java/script/INS
Const MAX_PATH = 260
Const PassiveConnection As Boolean = True
Private Type FILETIME
dwLowDateTime As Long
dwHighDateTime As Long
End Type
Private Type WIN32_FIND_DATA
dwFileAttributes As Long
ftCreationTime As FILETIME
ftLastAccessTime As FILETIME
ftLastWriteTime As FILETIME
nFileSizeHigh As Long
nFileSizeLow As Long
dwReserved0 As Long
dwReserved1 As Long
cFileName As String * MAX_PATH
cAlternate As String * 14
End Type
Private Declare Function InternetCloseHandle Lib "wininet.dll" (ByVal hInet As Long) As Integer
Private Declare Function InternetConnect Lib "wininet.dll" Alias "InternetConnectA" (ByVal hInternetSession As Long, ByVal sServerName As String, ByVal nServerPort As Integer, ByVal sUserName As String, ByVal sPassword As String, ByVal lService As Long, ByVal lFlags As Long, ByVal lContext As Long) As Long
Private Declare Function InternetOpen Lib "wininet.dll" Alias "InternetOpenA" (ByVal sAgent As String, ByVal lAccessType As Long, ByVal sProxyName As String, ByVal sProxyBypass As String, ByVal lFlags As Long) As Long
Private Declare Function FtpSetCurrentDirectory Lib "wininet.dll" Alias "FtpSetCurrentDirectoryA" (ByVal hFtpSession As Long, ByVal lpszDirectory As String) As Boolean
Private Declare Function FtpGetCurrentDirectory Lib "wininet.dll" Alias "FtpGetCurrentDirectoryA" (ByVal hFtpSession As Long, ByVal lpszCurrentDirectory As String, lpdwCurrentDirectory As Long) As Long
Private Declare Function FtpCreateDirectory Lib "wininet.dll" Alias "FtpCreateDirectoryA" (ByVal hFtpSession As Long, ByVal lpszDirectory As String) As Boolean
Private Declare Function FtpRemoveDirectory Lib "wininet.dll" Alias "FtpRemoveDirectoryA" (ByVal hFtpSession As Long, ByVal lpszDirectory As String) As Boolean
Private Declare Function FtpDeleteFile Lib "wininet.dll" Alias "FtpDeleteFileA" (ByVal hFtpSession As Long, ByVal lpszFileName As String) As Boolean
Private Declare Function FtpRenameFile Lib "wininet.dll" Alias "FtpRenameFileA" (ByVal hFtpSession As Long, ByVal lpszExisting As String, ByVal lpszNew As String) As Boolean
Private Declare Function FtpGetFile Lib "wininet.dll" Alias "FtpGetFileA" (ByVal hConnect As Long, ByVal lpszRemoteFile As String, ByVal lpszNewFile As String, ByVal fFailIfExists As Long, ByVal dwFlagsAndAttributes As Long, ByVal dwFlags As Long, ByRef dwContext As Long) As Boolean
Private Declare Function FtpPutFile Lib "wininet.dll" Alias "FtpPutFileA" (ByVal hConnect As Long, ByVal lpszLocalFile As String, ByVal lpszNewRemoteFile As String, ByVal dwFlags As Long, ByVal dwContext As Long) As Boolean
Private Declare Function InternetGetLastResponseInfo Lib "wininet.dll" Alias "InternetGetLastResponseInfoA" (lpdwError As Long, ByVal lpszBuffer As String, lpdwBufferLength As Long) As Boolean
Private Declare Function FtpFindFirstFile Lib "wininet.dll" Alias "FtpFindFirstFileA" (ByVal hFtpSession As Long, ByVal lpszSearchFile As String, lpFindFileData As WIN32_FIND_DATA, ByVal dwFlags As Long, ByVal dwContent As Long) As Long
Private Declare Function InternetFindNextFile Lib "wininet.dll" Alias "InternetFindNextFileA" (ByVal hFind As Long, lpvFindData As WIN32_FIND_DATA) As Long
Private Sub Command1_Click()
Dim hConnection As Long, hOpen As Long, sOrgPath As String
Dim FTPServer As String
Dim FTPLogin As String
Dim FTPPassword As String
Dim lpszRemoteDirectory As String
Dim lpszLocalFile As String
Dim lpszLocalFileGet As String
Dim lpszRemoteFile As String
Dim lpszNewRemoteFile As String
FTPServer = ""
FTPLogin = ""
FTPPassword = ""
lpszRemoteDirectory = "" 'директория, для сохранения файла
lpszLocalFile = "" 'локальный файл, который необходимо закачать
lpszRemoteFile = "" 'имя, под которым сохраним закачиваемый файл
lpszNewRemoteFile = "" 'для переименования
lpszLocalFileGet = "" 'файл, в который закачаем с ftp сервера
'Открываем соединение с интернетом
hOpen = InternetOpen("sample program", INTERNET_OPEN_TYPE_PRECONFIG, vbNullString, vbNullString, 0)
'Соединяемся с FTP сервером
hConnection = InternetConnect(hOpen, FTPServer, INTERNET_DEFAULT_FTP_PORT, FTPLogin, FTPPassword, INTERNET_SERVICE_FTP, IIf(PassiveConnection, INTERNET_FLAG_PASSIVE, 0), 0)
'Создаем буфер для запоминания оригинальной текущей директории
sOrgPath = String(MAX_PATH, 0)
'Получаем текущую директорию
Call FtpGetCurrentDirectory(hConnection, sOrgPath, Len(sOrgPath))
'Создаем новую директорию lpszRemoteDirectory
Call FtpCreateDirectory(hConnection, lpszRemoteDirectory)
'Меняем текущую директорию на root/%lpszRemoteDirectory%
Call FtpSetCurrentDirectory(hConnection, lpszRemoteDirectory)
'Заливаем файл lpszLocalFile
Call FtpPutFile(hConnection, lpszLocalFile, lpszRemoteFile, FTP_TRANSFER_TYPE_UNKNOWN, 0)
'Переименовываем файл lpszRemoteFile на lpszNewRemoteFile
Call FtpRenameFile(hConnection, lpszRemoteFile, lpszNewRemoteFile)
'Перечисляем все файлы текущей директории (root/%lpszRemoteDirectory%)
Call EnumFiles(hConnection)
'Получаем файл с FTP сервера
Call FtpGetFile(hConnection, lpszNewRemoteFile, lpszLocalFileGet, False, 0, FTP_TRANSFER_TYPE_UNKNOWN, 0)
'Удаляем файл с FTP сервера
Call FtpDeleteFile(hConnection, lpszNewRemoteFile)
'Восстанавливаем оригинальную (сохраненную ранее) текущую директорию
Call FtpSetCurrentDirectory(hConnection, sOrgPath)
'Удаляем созданную нами директорию lpszRemoteDirectory
Call FtpRemoveDirectory(hConnection, lpszRemoteDirectory)
'Закрываем соединение с FTP сервером
Call InternetCloseHandle(hConnection)
'Закрываем соединение с интернетом
Call InternetCloseHandle(hOpen)
End Sub
Public Sub EnumFiles(hConnection As Long)
Dim pData As WIN32_FIND_DATA, hFind As Long, lRet As Long
'Устанавливаем графический режим
Me.AutoRedraw = True
'Создаем буффер
pData.cFileName = String(MAX_PATH, 0)
'Ищем имя первого файла
hFind = FtpFindFirstFile(hConnection, "*.*", pData, 0, 0)
'Если файл не найден, тогда завершаем процедуру
If hFind = 0 Then Exit Sub
'Печатаем имя файла
Me.Print Left(pData.cFileName, InStr(1, pData.cFileName, String(1, 0), vbBinaryCompare) - 1)
Do
'Создаем буфер
pData.cFileName = String(MAX_PATH, 0)
'Ищем следующий файл
lRet = InternetFindNextFile(hFind, pData)
'Если файл не найден, тогда завершаем процедуру
If lRet = 0 Then Exit Do
'Печатаем имя файла
Me.Print Left(pData.cFileName, InStr(1, pData.cFileName, String(1, 0), vbBinaryCompare) - 1)
Loop
'Закрываем хендл поиска (первого файла)
Call InternetCloseHandle(hFind)
End Sub
Sub ShowError()
Dim lErr As Long, sErr As String, lenBuf As Long
'Получаем требуемый размер буфера
Call InternetGetLastResponseInfo(lErr, sErr, lenBuf)
'Создаем буфер необходимого размера
sErr = String(lenBuf, 0)
'Получаем информацию о последнем запросе
Call InternetGetLastResponseInfo(lErr, sErr, lenBuf)
'Показываем информацию о последнем запросе
Call MsgBox("Ошибка " + CStr(lErr) + ": " + sErr, vbOKOnly + vbCritical)
End Sub
Сейчас этот форум просматривают: Yandex-бот и гости: 72