Search code examples
c#textboxfile.readalllines

C# Cant find file (read from serial port)


I´m trying to open a file named the same as a bar code but I get the error that the file cannot be found?

I use this line to read the file:

string[] DxfFile = System.IO.File.ReadAllLines(textBoxBarCodeScanner.Text);

It works fine and open the file correctly if I assign the text box with:

textBoxBarCodeScanner.Text = (@"PLANKA.DXF");

I use these lines to read from the serial port:

RecievedData = RecievedData.Replace("\r\n", "").Replace("\r", "").Replace("\n", "");
textBoxBarCodeScanner.Text = (@RecievedData);

I had to remove /r first but it did not help. I´m kind a beginner so I´m not so good at finding the right debug information for you so here is what I got and please tell me where I found more useful information. If I break at the exection and look at "locals" I have a row that says text, and there I got "PLANKA.DFX" which seem to be correct.

Debug error message is as follow:

Additional information: Could not find file E:\Win7\Google Drive\Visual Studio 2013 Projects\Husmaskin GUI\Husmaskin GUI\bin\Debug\PLANKA.DFX.

This works (@"PLANKA.DXF"): Working textbox

This does not (@RecievedData)?? Not working textbox


Solution

  • In your screenshots, you have two different values for the file extension: DXF and DFX.

    There may be extra whitespace around the incoming text, so I would suggest also adding .Trim() to your code.

    I would also suggest checking for the file in your code and creating an error message that is more useful to you:

    var filename = txtFoo.Text;
    if (!File.Exists(filename))
         throw new Exception($"Could not find file '{filename}'");