Search code examples
c#wpfstringftpstreamreader

How to: Save a StreamReader content in a string


How to: Save a StreamReader content in a string

I am trying to save a StreamReader content in a string. Unfortunately, I am not allowed to save the content, because the object seems to be lost (coming from a FTP server).

Error message GERMAN: Auf das verworfene Objekt kann nicht zugegriffen werden. Objektname: "System.Net.Sockets.NetworkStream".

Error message ENGLISH: There is no access to the castaway object. Object name: "System.Net.Sockets.NetworkStream".

StreamReader streamReader = new StreamReader(responseStream);
string text = streamReader.ReadToEnd();

The error is from line 2.


Edit:

public void DownloadFileWithFtp()
    {
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://XYZ.bplaced.net/Testumgebung/Texte/" + comboBox_DataPool.SelectedValue);
        request.Credentials = new NetworkCredential("BN", "PW");
        request.Method = WebRequestMethods.Ftp.DownloadFile;

        FtpWebResponse response = (FtpWebResponse)request.GetResponse();
        Stream responseStream = response.GetResponseStream();

        StreamReader streamReader = new StreamReader(responseStream);
        MessageBox.Show(streamReader.ReadToEnd());
        //textBoxText = streamReader.ReadToEnd();
        streamReader.Close();

        MessageBox.Show(response.StatusDescription);
        response.Close();
    }

Solution

  • If you inspect the responseStream returned from the GetResponseStream() method of the FtpWebResponse, you will notice that the boolean property CanSeek is false.

    Reading streams multiple times in this way would always result in an error. Before the next call to ReadToEnd() is done you should precede it with a call to Seek(0,0). However, in this case, a call to responseStream.Seek(0, 0); would result in an NotSupportedException being thrown.

    Assigning the result once to an intermediate variable would work. Also use Using blocks rather than the Close() method:

    public void DownloadFileWithFtp() {
      FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://XYZ.bplaced.net/Testumgebung/Texte/" + comboBox_DataPool.SelectedValue);
      request.Credentials = new NetworkCredential("BN", "PW");
      request.Method = WebRequestMethods.Ftp.DownloadFile;
    
      using(FtpWebResponse response = (FtpWebResponse)request.GetResponse()) {
        using(Stream responseStream = response.GetResponseStream()) {
          using(StreamReader streamReader = new StreamReader(responseStream)) {
            string content = streamReader.ReadToEnd();
            MessageBox.Show(content);
            textBox.Text = content;
          }
        }
        MessageBox.Show(response.StatusDescription);
      }
    }