简体   繁体   English

从文件读取时,C#双引号路径名被转义

[英]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 \\ test.tiff
C:\\test\\anothertest.tiff C:\\ test \\ anothertest.tiff
C:\\test\\lasttest.tiff C:\\ test \\ lasttest.tiff

These get read in fine by my code ("C:\\\\test\\\\test.tiff" etc) 这些可以通过我的代码(“ C:\\\\ test \\\\ test.tiff”等)很好地读取。

However, if I have the following input file: 但是,如果我有以下输入文件:
"C:\\test with spaces\\test.tiff" “ C:\\ test with spaces \\ test.tiff”
"C:\\test with spaces\\anothertest.tiff" “ C:\\用空格测试\\ anothertest.tiff”
"C:\\test with spaces\\lasttest.tiff" “ C:\\ test with spaces \\ lasttest.tiff”

These get read in double-quotes and all ("\\"C:\\\\test with spaces\\\\test.tiff\\"" etc). 这些都用双引号和所有引号(“ \\” C:\\\\ test带空格\\\\ test.tiff \\“”等)读取。 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"; 字符串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,"\\"","") 如果每行只有一个文件,则可以执行Regex.Replace(PathLine,"\\"","")

If you don't you will need to split every time PathLine.Split(new string[] { "\\" ", "\\"\\n" }, StringSplitOptions.RemoveEmptyEntries); 如果不这样做,则每次都要分割PathLine.Split(new string[] { "\\" ", "\\"\\n" }, StringSplitOptions.RemoveEmptyEntries); then strip out the beginning " 然后删除开头

I think RegEx is quite heavy compared to a simple replace, so 与简单的替换相比,我认为RegEx相当繁重,所以

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

Or similar would be my suggestion. 或类似的建议。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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