sftp download yields corrupt files

Jun 20, 2014 at 6:17 PM
I am trying to pull some files off a server. The files appear to download correctly without issue--they have the correct size and name. However none of them will open. When I look at any of the files in a text editor, they are full of null characters. I know it's not a problem with the files themselves, because I am able to pull them down manually and they open just fine.

Here's the relevant part of my C# code:
           using (SftpClient sftp = new SftpClient(hostname, username, password))
            {
                sftp.Connect();
                List<SftpFile> files = new List<SftpFile>();
                foreach (SftpFile sftpFile in sftp.ListDirectory(fileDir))
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        var asynchDownload = sftp.BeginDownloadFile(sftpFile.FullName, ms, null, null);
                        var sftpAsynch = asynchDownload as Renci.SshNet.Sftp.SftpDownloadAsyncResult;
                        while (!sftpAsynch.IsCompleted)
                        {
                            Console.Write(String.Format("\rDownloaded {0} of {1}.", sftpAsynch.DownloadedBytes, 0));
                        }
                        sftp.EndDownloadFile(asynchDownload);
                        using (FileStream file = new FileStream(stfpDestination + "\\" + sftpFile.Name, FileMode.Create, System.IO.FileAccess.Write))
                        {
                            byte[] bytes = new byte[ms.Length];
                            ms.Read(bytes, 0, (int)ms.Length);
                            file.Write(bytes, 0, bytes.Length);
                            ms.Close();
                        }
                    }
                }
                sftp.Disconnect();
            }
Thanks!
Coordinator
Jun 22, 2014 at 9:57 AM
You may want to reset the position of the MemoryStream after the download has completed :p
Jun 23, 2014 at 4:03 PM
I really don't understand the different IO stream types very well, but a working solution I found was getting rid of the memory stream altogether and downloading directly to a file stream. The only benefits of using memory streams I have read about are performance, but this solution works plenty fast for my needs.
Marked as answer by asmyth on 6/23/2014 at 9:03 AM