Stream problem (General questions)
I'm currently evaluating the FtpDLX.Net component. I need to be able to retrieve a (text) file from a SFTP server and save it to a database. This is for a middle tier component and I do not want to save it to a file.
I am able to send a file from a stream using PutFile, but when I try to retrieve a file, the stream is closed after the GetFile call and I get a System.ObjectDisposedException: Cannot access a closed Stream exception.
Here's the code, with all my exception handling, etc. removed...
[code]
public class FtpHelper {
private FtpDLX _ftpConn;
public FtpHelper(string connectToServer, string ftpLogin, string ftpPassword, bool isSFTP, bool usePassive) {
_ftpConn = new FtpDLX();
_ftpConn.Blocking = true;
_ftpConn.Hostname = connectToServer;
_ftpConn.Login = ftpLogin;
_ftpConn.Password = ftpPassword;
_ftpConn.Passive = usePassive;
_ftpConn.Protocol = isSFTP ? Protocols.SFTP : Protocols.FTP;
_ftpConn.Connect();
}
/// <summary>
/// Sends a string to the server as a file.
/// </summary>
public bool SendTextAsFile(string text, string fileName, string remotePath) {
try {
_ftpConn.TransferMode = TransferModes.AscII;
MemoryStream stream = new MemoryStream(Encoding.ASCII.GetBytes(text));
_ftpConn.LocalPath = fileName;
_ftpConn.PutFile(stream, remotePath);
stream.Close();
}
catch {
return false;
}
return true;
}
// Want this function to pickup the remote CSV file and
// return it as a string
public string PickupFileToString(string folder, string fileName) {
MemoryStream stream = new MemoryStream();
_ftpConn.TransferMode = TransferModes.AscII;
// I have to have this here or I get a
// WeOnlyDo.InvalidSettingException, even though I'm not saving
// the file?
_ftpConn.LocalPath = fileName;
// filename example: /out/batch00002.csv
_ftpConn.GetFile(stream, folder + / + fileName);
// Stream is not readable here... getting ObjectDisposedException
// I have tried using other GetFile calls
//(ie GetFile(string localPath, string
// remotePath)) and they work fine, so I know the filename is
// correct and the file is on the server
return StreamToText(stream);
}
private static string StreamToText(Stream stream) {
string tempString = null;
int count = 0;
StringBuilder sb = new StringBuilder();
byte[] buf = new byte[8192];
do {
count = stream.Read(buf, 0, buf.Length);
if (count != 0) {
tempString = Encoding.ASCII.GetString(buf, 0, count);
sb.Append(tempString);
}
}
while (count > 0);
return sb.ToString();
}
public void Disconnect() {
_ftpConn.Disconnect();
}
~FtpHelper() {
if (_ftpConn.State != States.Disconnected)
_ftpConn.Disconnect();
}
}
[/code]