Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why File.OpenRead() appends relative path to the executable file?

Tags:

c#

.net

Why while using the following code

string filePath = @"‪C:\test\upload.pdf"
FileStream fs = File.OpenRead(filePath);

raises the following exception?

The filename, directory name, or volume label syntax is incorrect : 
'C:\ConsoleApp\bin\Debug\netcoreapp2.1\‪‪C:\test\upload.pdf'

From where the C:\ConsoleApp\bin\Debug\netcoreapp2.1\‪‪ directory comes from?

Update: The File.OpenRead() in my case, exists within in an dll & the filePath (‪C:\test\upload.pdf) is sent via the application that is using the dll.

like image 569
OrElse Avatar asked Sep 16 '25 10:09

OrElse


1 Answers

The string starts with an invisible character, so it's not a valid path. This

(int)@"‪C:\test\upload.pdf"[0]

Returns

8234

Or hex 202A. That's the LEFT-TO-RIGHT EMBEDDING punctuation character

UPDATE

Raymond Chen posted an article Why is there an invisible U+202A at the start of my file name?.

We saw some time ago that you can, as a last resort, insert the character U+202B (RIGHT-TO-LEFT EMBEDDING) to force text to be interpreted as right-to-left. The converse character is U+202A (LEFT-TO-RIGHT EMBEDDING), which forces text to be interpreted as left-to-right.

The Security dialog box inserts that control character in the file name field in order to ensure that the path components are interpreted in the expected manner. Unfortunately, it also means that if you try to copy the text out of the dialog box, the Unicode formatting control character comes along for a ride. Since the character is normally invisible, it can create all sorts of silent confusion.

(We’re lucky that the confusion was quickly detected by Notepad and the command prompt. But imagine if you had pasted the path into the source code to a C program!)

In the 4 years since that article Notepad got UTF8 support so the character isn't replaced by a question mark. Pasting into the current Windows Console with its incomplete UTF8 support still replaces the character.

like image 115
Panagiotis Kanavos Avatar answered Sep 18 '25 09:09

Panagiotis Kanavos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!