This below code snippet will be so useful for
copying the file from one physical location to another physical location in a
server. ASP.net has inbuilt classes IO.Filestream
that is so useful for various file manipulation function.
Code
Public Shared Sub CopyFiles(ByVal srcPath_File As String,ByVal dstPath_File As String)
Code
Public Shared Sub CopyFiles(ByVal srcPath_File As String,ByVal dstPath_File As String)
Dim oFile As System.IO.FileInfo
Dim oFileStream As System.IO.FileStream = Nothing
Dim oFileStreamR As System.IO.FileStream = Nothing
Try
oFile = New System.IO.FileInfo(srcPath_File)
oFileStream = oFile.OpenRead()
Dim lBytes As Long = oFileStream.Length
Dim fileData(lBytes) As Byte
oFileStream.Read(fileData, 0, lBytes)
If File.Exists(dstPath_File) ThenFile.Delete(dstPath_File)
oFileStreamR = New System.IO.FileStream(dstPath_File,
System.IO.FileMode.OpenOrCreate)
oFileStreamR.Write(fileData, 0, fileData.Length)
oFileStreamR.Flush()
oFileStreamR.Close()
oFileStreamR.Dispose()
Catch ex As Exception
Throw ex
Finally
oFileStream.Close()
oFile = Nothing
If oFileStreamR IsNot Nothing Then
oFileStreamR = Nothing
End If
End Try
End Sub
Explanation of the code as below,
- Use System.IO namespace
- Create an instance for the fileinfo class to get the file information of the source file.
- Create two instances of filestream one for reading and other for writing the file.
- Find the length of the filestream object and store in a byte variable.
- Check to see the file already exist in the destination location. If file already exist in the location then delete the file.
- Using the filestream read instance read the content of the file and write the content in the target location using the filestream write instance.
- Flush and close the filestream write instance.
- Finally close the filestream instances.
No comments:
Post a Comment