简体   繁体   中英

C# double-quoted path name being escaped when read from file

I am trying to read in a text input file that contains a list of filenames (one per line). However, I am running into an issue if the user double-quotes the path (because it has a space in it).

For example, a normal input file might have:
C:\\test\\test.tiff
C:\\test\\anothertest.tiff
C:\\test\\lasttest.tiff

These get read in fine by my code ("C:\\\\test\\\\test.tiff" etc)

However, if I have the following input file:
"C:\\test with spaces\\test.tiff"
"C:\\test with spaces\\anothertest.tiff"
"C:\\test with spaces\\lasttest.tiff"

These get read in double-quotes and all ("\\"C:\\\\test with spaces\\\\test.tiff\\"" etc). This becomes a problem when I try to open the files (I understandably get invalid character exceptions). My question is, how do I fix this? I want to allow users to input quoted strings and handle them correctly. My first impression was to just write a little method that strips off beginning or ending quotes, but I thought there might be a better way.

无需RegEx ,只需简单的Replace

var s = s.Replace("\"", "");

My first impression was to just write a little method that strips of beginning or ending quotes...

Yeah, that's what I'd do, too. =)

Maybe try using string literals?

string bob = @"c:\\some file\\some document";

The @ escapes these backslash problems.

If you have only one file per line you can just do Regex.Replace(PathLine,"\\"","")

If you don't you will need to split every time PathLine.Split(new string[] { "\\" ", "\\"\\n" }, StringSplitOptions.RemoveEmptyEntries); then strip out the beginning "

I think RegEx is quite heavy compared to a simple replace, so

File.ReadAllText(path.Replace('"',''));

Or similar would be my suggestion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM