如何将文件复制/替换到 VB.NET 中的文件夹中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14978894/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 16:41:30  来源:igfitidea点击:

How to copy/replace a file into a folder in VB.NET?

vb.net

提问by thotwielder

I used File.Copy(source, target, True), where sourceis a full path name, like c:\source.txtand targetis a folder, which may contain the same named file. I want to copy source.txtto a target folder and overwrite if the file already exists.

我使用了File.Copy(source, target, True), 其中source是完整路径名,例如c:\source.txttarget是文件夹,其中可能包含同名文件。source.txt如果文件已经存在,我想复制到目标文件夹并覆盖。

But I got the error:

但我得到了错误:

'Target is a folder, not a file'

'目标是一个文件夹,而不是一个文件'

回答by SysDragon

Target must contain a filename too:

目标也必须包含文件名:

sSource = "C:\something.txt"
sTarget = "C:\folder\something.txt"

File.Copy(sSource, sTarget, True)

If you want to programatically have the same filename just do:

如果您想以编程方式具有相同的文件名,请执行以下操作:

File.Copy(sSource, Path.Combine(sFolder, Path.GetFileName(sSource)), True)

Read the MSDN Documentationto have examples and information about exceptions and use of the method.

阅读MSDN 文档以获取有关异常和方法使用的示例和信息。

回答by Meisam Rasouli

You can also use a FileStream for reading and writing file contents. If you use a file stream you can read and write all types of binary files, not just text files.

您还可以使用 FileStream 来读取和写入文件内容。如果您使用文件流,您可以读写所有类型的二进制文件,而不仅仅是文本文件。

Use the following procedure:

使用以下程序:

''' <summary>
    ''' copies a file from one location to another
    ''' </summary>
    ''' <param name="inputPath">full path to the input file</param>
    ''' <param name="outputPath">full path to the output file</param>
    ''' <param name="bufferSize">the size in bytes as an integer that will be read and written at a time from input file and to the output file</param>
    ''' <param name="overwrite">overwrite the output file if it already exists</param>
    ''' <returns></returns>
    Public Function CopyFile(ByVal inputPath As String,
                             ByVal outputPath As String,
                             ByVal bufferSize As Integer,
                             Optional ByVal overwrite As Boolean = False) As Boolean

        Dim PathIsClear As Boolean = True, SucOpt As Boolean = False
        Dim inputByteReaderObj As System.IO.FileStream = System.IO.File.Open(inputPath, IO.FileMode.Open) 'open a file stream for reading bytes from the input file
        Dim endofSize As Integer = My.Computer.FileSystem.GetFileInfo(inputPath).Length
        If overwrite AndAlso FileExists(outputPath) Then
            'if file exits, delete the output file
            PathIsClear = False
            PathIsClear = DeleteFilesOnDisk(outputPath) ' Delete the output file if it already exists
        End If

        ' Adjust array length for VB array declaration.

        Dim allBytesRead As Integer = 0, sucessfullBytes As Integer = 0, bytes As Byte() 'The byte array
        If bufferSize > endofSize Then
            bufferSize = endofSize
        End If
        If bufferSize >= 1 Then
            bytes = New Byte(bufferSize - 1) {} 'The byte array; create a byte array that will hold the data in length equal to the bufferSize; the array index starts at 0;
            If PathIsClear Then
                While inputByteReaderObj.Read(bytes, 0, bufferSize) > 0
                    'read bytes consequtively from the input file, each time read bytes equal in length to bufferSize
                    Try
                        My.Computer.FileSystem.WriteAllBytes(outputPath, bytes, True) ' Append to the file contents
                        sucessfullBytes += bufferSize
                    Catch ex As Exception
                        Stop
                    End Try
                    allBytesRead += bufferSize
                    If (allBytesRead + bufferSize) > endofSize Then
                        bufferSize = endofSize - allBytesRead 'change the size of the buffer match the end of the file
                    End If
                    If bufferSize >= 1 Then
                        bytes = New Byte(bufferSize - 1) {} 'the array index starts at zero, the bufferSize starts at 1
                    End If
                    If allBytesRead >= endofSize Or bufferSize = 0 Then
                        'the reader has already reached the end of file, exit the reader loop
                        Exit While
                    End If
                End While
                If sucessfullBytes = allBytesRead Then
                    SucOpt = True
                End If
            End If
        Else
            'write an empty file
            Try
                System.IO.File.Create(outputPath) 'Create an empty file because the size of the input file is zero
            Catch ex As Exception
                'an error occured in creating an empty file
            End Try
        End If

        inputByteReaderObj.Close()

        Return SucOpt
    End Function