我不明白这段代码有什么问题

时间:2014-03-08 02:58:56

标签: vb.net forms copy directory

你能帮我解释一下这段代码吗?请不要给我一个负面的印记!!

If Not Directory.Exists("C:\Libraries\Documents\Backup - Advanced_Website_Blocker  Folder") Then
          Directory.CreateDirectory("C:\Libraries\Documents\Backup -  Advanced_Website_Blocker Folder")
    End If
    Dim FileToCopy As String
    Dim NewCopy As String

    FileToCopy = "C:\Windows\System32\drivers\etc\hosts"
    NewCopy = "C:\Libraries\Documents\Backup - Advanced_Website_Blocker Folder\hosts"

    If System.IO.File.Exists(FileToCopy) = True Then

        System.IO.File.Copy(FileToCopy, NewCopy)
        MsgBox("File Copied")

    Else : MsgBox("No Folder Found!")

    End If

4 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

 FileToCopy = "C:\Windows\System32\drivers\etc\hosts"

是一个文件夹

 If System.IO.File.Exists(FileToCopy) 

正在检查是否存在文件而不是文件夹

答案 2 :(得分:0)

您需要检查文件是否存在,如果存在,请覆盖它。您可以使用覆盖文件的File.Copy方法的重载:

System.IO.File.Copy(FileToCopy, NewCopy, True)

答案 3 :(得分:0)

检查要导入的库,请参阅下面的示例代码:

' For File.Exists, Directory.Exists 

Imports System
Imports System.IO
Imports System.Collections

Public Class RecursiveFileProcessor

    Public Overloads Shared Sub Main(ByVal args() As String)
        Dim path As String
        For Each path In args
            If File.Exists(path) Then
                ' This path is a file.
                ProcessFile(path)
            Else
                If Directory.Exists(path) Then
                    ' This path is a directory.
                    ProcessDirectory(path)
                Else
                    Console.WriteLine("{0} is not a valid file or directory.", path)
                End If
            End If
        Next path
    End Sub 'Main


    ' Process all files in the directory passed in, recurse on any directories 
    ' that are found, and process the files they contain.
    Public Shared Sub ProcessDirectory(ByVal targetDirectory As String)
        Dim fileEntries As String() = Directory.GetFiles(targetDirectory)
        ' Process the list of files found in the directory.
        Dim fileName As String
        For Each fileName In fileEntries
            ProcessFile(fileName)

        Next fileName
        Dim subdirectoryEntries As String() = Directory.GetDirectories(targetDirectory)
        ' Recurse into subdirectories of this directory.
        Dim subdirectory As String
        For Each subdirectory In subdirectoryEntries
            ProcessDirectory(subdirectory)
        Next subdirectory

    End Sub 'ProcessDirectory

    ' Insert logic for processing found files here.
    Public Shared Sub ProcessFile(ByVal path As String)
        Console.WriteLine("Processed file '{0}'.", path)
    End Sub 'ProcessFile
End Class 'RecursiveFileProcessor

http://msdn.microsoft.com/en-us/library/system.io.directory.exists%28v=vs.110%29.aspx?cs-save-lang=1&cs-lang=vb#code-snippet-1