I am having trouble with opening up a StreamReader object in C#. I always receive the exception Illegal characters in path. The only way I can get it to work is if I use the entire path name using the @ symbol to not escape any \ characters in the file path. However, this doesn't really help me because I start with the two separate variables for the file's path and the file's name as output from another method (which can not be changed).
I've gone through eight permutations that all failed, which are commented out below for reference. For the sake of readability here, pretend I'm declaring dirIni and fileIni instead of receiving their values as output from another method. With that said, both declaration style 1 and 2 failed using all four concatenation methods. What is going on here? I've pretty much seen all four concatenation methods work in other examples.
EDIT: I've simplified the code to show 1 version of what breaks for me:
string dirIni = @"C:\Users\Dan\AppData\Local\MyApp 4.0\INI\";
string fileIni = @"PWTRANSACTION.INI";
try
{
string transIniFullFileName = Path.Combine(dirIni, fileIni);
using (StreamReader file = new StreamReader(transIniFullFileName))
{
// do StreamReader stuff...
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Here is the exception's stack trace:
at System.IO.Path.CheckInvalidPathChars(String path)
at System.IO.Path.GetFileName(String path)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options)
at System.IO.StreamReader..ctor(String path, Encoding encoding, Boolean detectEncodingFromByteOrderMarks, Int32 bufferSize)
at System.IO.StreamReader..ctor(String path)
at TestApp.Form1.btnTestRead_Click(Object sender, EventArgs e) in C:\Users\Dan\TestApp\Form1.cs:line 4977
The issue was the method was returning a string which had a Field Separator character at the end, and that was the illegal character. I was also using these strings in my test code. I pasted my code into notepad++ and toggled on "Show Hidden Characters" and I could see the FS character then. After removing the FS, everything ran properly. Thank you all for helping me test the code, especially @Dynguss.
Any time VS gives the Illegal Character exception, check for potential hidden characters!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With