Not logged in - Login
< back

Create a function to read a FileStream and return a string

Sample function on how to read a FileStream object and return a string.

public static string ReadFileStream(System.IO.FileStream fs)
{
       //
   // declare a stringbuilder class to hold our data
       StringBuilder
   StringBuilder sbWork = new StringBuilder();

       //

   // make sure our StringBuilder work variable is big enough
       sbWork.EnsureCapacity((int)fs.Length);
       //
   sbWork.EnsureCapacity((int)fs.Length);
   // empty the work variable
       sbWork.Length
   sbWork.Length = 0;

       int

   int nByte; // variable to hold the current byte.
       bool
   bool bReturnNull = true; // holds flag to determine if the function should return NULL

       //

   // read each byte in the file stream.
       while
   while ((nByte = fs.ReadByte()) >= 0)
       {
              //
   {
      // set the flag so we know to NOT return NULL.
              bReturnNull
      bReturnNull = false;

              //

      // convert the byte to a character.
              char
      char cTemp = (char)nByte;
              //
      // append the character to our work variable.
              sbWork.Append(cTemp);                            
       }

                     
       if
      sbWork.Append(cTemp);            
   }

         
   if (bReturnNull)
       {
              return
   {
      return null;
       }
       else
       {
              return
   }
   else
   {
      return sbWork.ToString();
       }
   }
}