doug 0

doug 0

  • NA
  • 14
  • 0

Filestream object not in scope, need work around ideas

Sep 2 2005 12:49 PM
Hi everyone, My problem exists with creating a Filestream and BinaryWriter objects in a C# app that collects real time data very quickly. I only collect want to create the file if a specific sensor is being used. However, C# does not allow the the creation of either of these objects with the ability to use them later on in the method because the specific object was not initialized. Let me give a sample piece of code...
private void Collect_data()

 int y_1 =0; //collected integer value to be written to file 
 
 if(sensor1_on ==true) 
 { 
   FileStream writeMyFileGPS = new FileStream(fileNameGPS, FileMode.Append,FileAccess.Write);
   BinaryWriter sr= new BinaryWriter(writeMyFileGPS);
 } 

  //WRITE COLLECTED DATA TO FILE IF USING THIS SENSOR 
  if(sensor1_on==true)  
  { 
    sr.BaseStream.WriteByte((byte)(y_1 & 0x000000FF));
   } 

   //END OF METHOD CLOSE HANDLERS 
   if(sensor1_on==true)  
   { 
     sr.Close();
     writeMyFileGPS.Close();
   }

}//END-COLLECT DATA METHOD
The problem lies in that C# will not let you create the object in the if statement and then use it later in the method. It does not have scope outside the if statement in which it was created (CORRECT???) (you could do this in C).
 
Now, I could create the objects within the if statements where I write the binary data to the file, but this takes an eternity about 0.001 seconds every time I get data in and it kills the throughput in my app. I don't want to create the the file if I don't have to so any work arounds would be much appreciated. Thank you...

Answers (3)