0

I have created an app in which I read a sensor and write the sensor data to text. My code for writing to the text file is:

    private int outputData
    {
        set
        {
            if (InvokeRequired)
            {
                BeginInvoke(new Action(() => labelOutputRead.Text = Convert.ToString(value / 10)), null);
                chart1.Invoke((MethodInvoker)(() => chart1.Series["Pressure"].Points.AddXY(DateTime.Now.ToLongTimeString(), Convert.ToInt32(value) / 10)));
                TimeSpan ts = stopWatch.Elapsed;
                TimeSpan diff = new TimeSpan(0, 0, 0, 1);
                TimeSpan timeDifference = ts.Subtract(interval);
                String timeElapsed = String.Format("{0:00}:{1:00}:{2:00}", ts.Hours, ts.Minutes, ts.Seconds);
                labelStopwatch.BeginInvoke((Action)delegate () { labelStopwatch.Text = "Data capture time: " + timeElapsed; });
                if (captureOn == true)
                {
                    if (timeDifference > diff)
                    {
                        File.Create(path).Dispose();
                        using (StreamWriter writer = new StreamWriter(path, append: true))
                        {
                            writer.Write(timeElapsed + " " + Convert.ToInt32(labelOutputRead.Text) + " " + Convert.ToInt32(labelVacuumRead.Text) + " " + Convert.ToInt32(labelPressureRead.Text) + " " + Convert.ToInt32(pressureInput) / 10 + "\n");
                        }
                        interval = ts;
                    }
                }
                if (chart1.Series[0].Points.Count > 20)
                {
                    chart1.Invoke((MethodInvoker)(() => chart1.Series[0].Points.RemoveAt(0)));
                }
            }
        }
    }

Here I am constantly reading the data from the sensor and plotting it in chart1, and it starts capturing the data when captureOn is true. The bool captureOn becomes true when the user presses a "Capture" button.

The issue is that when I start capturing data and use other functions in the application, such as toggle a camera on/off or take a screenshot, I randomly (seemlingy randomly anyway) get the error message:

System.IO.IOException: 'The process cannot access the file 'C:\Users...test.txt' because it is being used by another process.'

The event that seems to consitently reproduce this error is:

    private void buttonCamera_Click(object sender, EventArgs e)
    {
        if (cameraOn == false)
        {
            cameraOn = true;
            buttonCamera.Text = "Disconnect camera";
            if (String.IsNullOrEmpty(comboBoxCamera.Text))
            {
                MessageBox.Show("No camera selected", "VALUE ERROR", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            else
            {
                string cameraName = comboBoxCamera.Text;
                videoCaptureDevice = new VideoCaptureDevice(filterInfoCollection[comboBoxCamera.SelectedIndex].MonikerString);
                videoCaptureDevice.NewFrame += FinalFrame_NewFrame;
                videoCaptureDevice.VideoResolution = videoCaptureDevice.VideoCapabilities[2];
                videoCaptureDevice.Start();
                labelCameraConnection.Text = "Connected to " + cameraName;
            }
        }
        else
        {
            cameraOn = false;
            buttonCamera.Text = "Connect camera";
            labelCameraConnection.Text = "Camera disconnected";
            videoCaptureDevice.Stop();
            if (pictureBoxCamera.Image != null)
            {
                pictureBoxCamera.Image.Dispose();
            }
            pictureBoxCamera.Image = null;
        }
    }

Why do I get this error message when I use other functions such as toggle a camera ON/OFF? And how can I make the data capture more robust to never get this error?

Many thanks!

  • It did actually, although I am not sure why and would like to know. I just needed create a filestream with settings: using (FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.ReadWrite)) and create my StreamWriter from the FileStream. The error disappeared. But why? – AlexanderEngman Mar 23 '23 at 10:22

0 Answers0