-2

I am having issues with illegal characters I am trying to import two documents as lists or arrays. a document is chosen from the file browser and the path is formatted ready to be read in.

I keep getting illegal character errors when it tries to step through the read all lines.

{
        OpenFileDialog fdlg = new OpenFileDialog();
        fdlg.Title = "C# Corner Open File Dialog";
        fdlg.InitialDirectory = @"c:\";
        fdlg.Filter = "All files (*.*)|*.*|All files (*.*)|*.*";
        fdlg.FilterIndex = 2;
        fdlg.RestoreDirectory = true;

        if (fdlg.ShowDialog() == DialogResult.OK)
        {
            textBox2.Text = fdlg.FileName;
            var gold1 = "@" + '"' + fdlg.FileName + '"';

            textBox4.Text = gold1;
            textBox5.Text = gold1;

            string[] lines = System.IO.File.ReadAllLines(gold1);
            
            //foreach (var line in lines)
            {
              //  Console.WriteLine(line);
            }
        }
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
jimc
  • 13
  • 1
  • Does this answer your question? [How to remove illegal characters from path and filenames?](https://stackoverflow.com/questions/146134/how-to-remove-illegal-characters-from-path-and-filenames) – Raju Ahmed Oct 24 '21 at 16:17
  • 1
    Why do you add an @ and quotes to the file name? Why don't you just ReadAllLines from `fdlg.FileName` instead of using `gold1`? – Ian Mercer Oct 24 '21 at 16:24

1 Answers1

1

I think you're confused between getting compile time and run time strings into your program

When you write a code like this:

var filepath = @"c:\temp\my.txt";

The @" and " are NOT part of the path; they're instructions to the c# compiler "here is a string constant, do not perform any checking of the contents, looking for slashes to turn into new lines and tabs etc"

If the @ was not there then the compiler would look at the string, find \t in c:\temp and think you wanted it converting to a tab (and then it would complain about the \m from \my.txt not being a valid slash code but..). Putting an @ turns this behavior off so you don't have to write your paths in the uglier format of c:\\temp\\my.txt

When you show a file chooser and the user picks a file, the path of the file is in the .FileName property and is usable as it is - do not add a leading @" to it

Just do

 var lines = File.ReadAllLines(fdlg.FileName);

that is to say, the file chooser will have a valid path in already so you can just straight use it. Remember that you can only effectively ReadAllLines with text files; if these "documents" you mention are eg word documents then you'll need to read them with a dedicated library, but the process of using the FileName from the file chooser would remain the same

Caius Jard
  • 72,509
  • 5
  • 49
  • 80