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 sbWork = new StringBuilder();

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

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

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

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

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