Как скопировать HTML-файл вместе со всеми связанными изображениями и папками скриптов?
Я хочу скопировать файл HTML из одного места в другое, используя VB.net.
Когда я использую любой из трех файлов FileCopy, System.IO.File.Copy, My.Computer.FileSystem.CopyFile, он копирует только файл, а не папку "filename_files", которая содержит связанные изображения и сценарии.
То, что я хочу сделать программно, это скопировать a.html в другое место как b.html
когда я делаю это и открываю b.html, он открывает его без каких-либо изображений и сценариев.
Пожалуйста, помогите
2 ответа
Вы можете использовать следующие два метода, которые вместе могут копировать папку, которая включает в себя сценарии и изображения, таким образом, с помощью встроенного метода FileCopy
Скопируйте ваш HTML-файл и, используя приведенные ниже методы, скопируйте нужную папку.
Я нашел первый метод, который возвращает массив файлов по заданному пути здесь
Public Function FileList(Mask As String) As String()
Dim sWkg As String
Dim sAns() As String
Dim lCtr As Long
ReDim sAns(0) As String
sWkg = Dir(Mask, vbNormal)
Do While Len(sWkg)
If sAns(0) = "" Then
sAns(0) = sWkg
Else
lCtr = UBound(sAns) + 1
ReDim Preserve sAns(lCtr) As String
sAns(lCtr) = sWkg
End If
sWkg = Dir
Loop
FileList = sAns
End Function
Теперь, используя вышеуказанный метод и метод ниже, вы можете скопировать папку, указав путь к источнику и цели. Метод вернет логическое значение, указывающее, была ли скопирована папка или нет.
Public Function FolderCopy(ByVal SourceFolder As String, ByVal TargetFolder As String) As Boolean
Dim flist() As String
Dim sURL As String = New String(SourceFolder)
Dim tURL As String = New String(TargetFolder)
Dim i As Integer
Dim slashpos As Long
If Not Directory.Exists(tURL) Then
slashpos = InStrRev(sURL, "\") 'Get position of last occurrence if '\' in given path
If slashpos <> sURL.Length Then 'Check if URL does not have slash at its end
sURL = sURL & "\" 'Add slash at URL end
End If
flist = FileList(sURL)
slashpos = InStrRev(tURL, "\") 'Get position of last occurrence if '\' in given path
If slashpos = tURL.Length Then
tURL = tURL.Substring(0, tURL.Length - 1)
End If
slashpos = InStrRev(tURL, "\")
Try
Directory.CreateDirectory(tURL)
For i = 0 To flist.Length - 1
FileCopy(sURL & flist(i), tURL & "\" & flist(i))
Next
FolderCopy = True
Catch ex As Exception
FolderCopy = False
End Try
Else
FolderCopy = False
End If
End Function
Убедитесь, что вы включаете Imports System.IO
в начале урока перед использованием FolderCopy
метод, и обратите внимание, что оба эти метода должны быть включены.
' copy all files and subdirectories from the
' specified source to the specified destination.
Private Sub RecursiveCopyFiles( ByVal sourceDir As String, ByVal destDir As String, _
ByVal fRecursive As Boolean)
Dim i As Integer
Dim posSep As Integer
Dim sDir As String
Dim aDirs() As String
Dim sFile As String
Dim aFiles() As String
' Add trailing separators to the supplied paths if they don't exist.
If Not sourceDir.EndsWith(System.IO.Path.DirectorySeparatorChar.ToString()) Then
sourceDir &= System.IO.Path.DirectorySeparatorChar
End If
If Not destDir.EndsWith(System.IO.Path.DirectorySeparatorChar.ToString()) Then
destDir &= System.IO.Path.DirectorySeparatorChar
End If
' Recursive switch to continue drilling down into dir structure.
If fRecursive Then
' Get a list of directories from the current parent.
aDirs = System.IO.Directory.GetDirectories(sourceDir)
For i = 0 To aDirs.GetUpperBound(0)
' Get the position of the last separator in the current path.
posSep = aDirs(i).LastIndexOf("\")
' Get the path of the source directory.
sDir = aDirs(i).Substring((posSep + 1), aDirs(i).Length -(posSep + 1))
' Create the new directory in the destination directory.
System.IO.Directory.CreateDirectory(destDir + sDir)
' Since we are in recursive mode, copy the children also
RecursiveCopyFiles(aDirs(i), (destDir + sDir), fRecursive)
Next
End If
' Get the files from the current parent.
aFiles = System.IO.Directory.GetFiles(sourceDir)
' Copy all files.
For i = 0 To aFiles.GetUpperBound(0)
' Get the position of the trailing separator.
posSep = aFiles(i).LastIndexOf("\")
' Get the full path of the source file.
sFile = aFiles(i).Substring((posSep + 1), aFiles(i).Length - (posSep+ 1))
' Copy the file.
System.IO.File.Copy(aFiles(i), destDir + sFile)
Next i
End Sub