3
Answers

Filestream object not in scope, need work around ideas

Photo of doug 0

doug 0

19y
2.8k
1
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)

0
Photo of venkatesh p
NA 7 0 17y
thanks for your reply. i got it. but when i start the service "it shows some errors " please help me to rectify that. the errror was  service could not be started on this computer . since no timely fashion reply from service.
0
Photo of Scott Lysle
NA 28.5k 14.4m 17y
You can start by overriding the OnStart event for your service; in that code you can use Process.Start to kick on some other application (in the below example, I start internet explorer and pass it the URL for MSN as a argument so that whenever the service starts, it opens up MSN in an explorer window)
protected override void OnStart(string[] args) {  System.Diagnostics.Process.Start("iexplore.exe", "http://www.msn.com"); }   Process.Start accepts a couple of arguments, the first is the executable to launch (e.g., iexplore.exe in this example) and the second argument is any optional arguments that the executable may use (in this case, a URL).  Of course the executable can be any executable and may include a full path to that executable and the arguments to the executable are optional.