This project is read-only.

Text files get truncated

Jul 15, 2014 at 7:31 PM
Edited Jul 15, 2014 at 7:33 PM
I am trying to write some code that copies some .txt files from an FTP server to a local directory in my asp.net web application. The code seems to run fine, but the resulting files are only partially complete and half of the file is filled with whitespace. This is the code I am using:
  Dim ftp As New FtpClient

                ftp.Host = ConfigurationManager.AppSettings("FTPserver")
                ftp.Credentials = New NetworkCredential(ConfigurationManager.AppSettings("FTPuser"), ConfigurationManager.AppSettings("FTPpassword"))

                Dim fileCount As Integer = 0

                For Each item In ftp.GetListing("/IPRT")
                    If item.Type = FtpFileSystemObjectType.Directory Then
                        For Each innerItem In ftp.GetListing("/IPRT/" & item.Name)
                            If innerItem.Type = FtpFileSystemObjectType.File Then
                                SaveStreamToFile(path & innerItem.Name, ftp.OpenRead(innerItem.FullName))
                                ftp.Rename("/IPRT/" & item.Name & "/" & innerItem.Name, "/IPRT/" & item.Name & "/Archive/" & innerItem.Name)
                                fileCount = fileCount + 1
                            End If
                        Next
                    End If
                Next
                Return fileCount
            End If
and the SaveStreamToFile method:
Public Shared Sub SaveStreamToFile(ByVal path As String, ByVal stream As Stream)
        If stream.Length <> 0 Then
            Dim bytesInStream(stream.Length - 1) As Byte
            stream.Read(bytesInStream, 0, bytesInStream.Length)
            File.WriteAllBytes(path, bytesInStream)
        End If
    End Sub
Jul 16, 2014 at 6:09 PM
Aha, I just figured out the problem - I was forgetting to close the file stream. Adding
stream.Close()
at the end of my SaveStreamToFile method solves the issue.
Marked as answer by mbesemann on 7/16/2014 at 10:09 AM