Concatenate string literals with DirectoryInfo enumeration and adding quotation marks.

风流意气都作罢 提交于 2019-12-11 13:35:52

问题


This seems like such an obscure question, but here it goes:

Is there a way to concatenate String Literals with a DirectoryInfo enumeration (which contains a file path) while adding quotations around the file path? Further, how can I prevent backslashes from being doubled when converting a DirectoryInfo enumeration to a string? My situation is as follows:

DirectoryInfo filePathDirectory = new DirectoryInfo(filePath);
Process a = new Process();

a.StartInfo.FileName = "C:\\Windows\\system32\\lpr.exe";
a.StartInfo.Arguments = "-SServername.Domain.net -Plp " + "\"" + filePathDirectory + "\"";
a.StartInfo.UseShellExecute = false;
a.Start();
a.WaitForExit();

filePathDirectory starts with a value of:

{\\ServerName\Share\Folder\Folder\FileName.xls}

Which I think is converted into a string once concatenated into a.StartInfo.Arguments which is assigned the value of:

-SServername.Domain.net -Plp \"\\\\ServerName\\Share\\Folder\\Folder\\FileName.xls\"

This is bad because, the number of backslashes in the path doubled. How can I ensure no backslashes are added to the path?

On top of that, to add a quotation marks, I've used the backslash escape sequence; But the backslash from this escape sequence is inadvertently added to my string. How can I add quotation marks around the file path which is contained in a.StartInfo.Arguments?

P.S. I hope this makes sense, please ask questions if you need clarification.


回答1:


The backslashes are not doubled and the backslash of the quotes also "isn't there". You can verify it by Console.WriteLine(a.StartInfo.Arguments) or MessageBox.Show(a.StartInfo.Arguments).

What you are seeing - in the debugger I assume - is the representation of the string with the escape characters not translated - just as you would need to enter it in the IDE.

Example:

string s = "\"";

This will show in the debugger as "\"" but it will display on screen as ":



来源:https://stackoverflow.com/questions/12531976/concatenate-string-literals-with-directoryinfo-enumeration-and-adding-quotation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!