C#路径中存在非法字符

4

使用以下代码时,路径中出现了非法字符:

string fileNameExisting = Application.StartupPath + "\\CodesLocation\\Template.pdf";
PdfReader templateFile = new PdfReader(fileNameExisting);

我进行了几个变体测试:

string fileNameExisting = @Application.StartupPath + "\CodesLocation\Template.pdf";
PdfReader templateFile = new PdfReader(fileNameExisting);

但是仍然出现相同的非法错误。

有没有人可以帮助我看看我的代码是否有误?

谢谢。


5
为什么不输出fileNameExisting,这样我们就可以看到哪些非法字符了。 - Nick
请检查 Application.StartupPath 的值并分享。 - Romil Kumar Jain
这是 c:\Projects... 让我尝试答案,如果有问题就回复。 - kyusan93
它显示 C:\Projects\CodesLocation\Template.pdf... 仍然出现相同的非法错误。 - kyusan93
3个回答

11

我建议使用在.NET中连接路径的适当方法:Path.Combine

因此,

Path.Combine(Application.StartupPath, "CodesLocation","Template.pdf");

让我拿到笔记本电脑时再试一下...无论如何,感谢您的及时帮助。 - kyusan93
它显示 C:\Projects\CodesLocation\Template.pdf... 它仍然得到相同的非法错误。 - kyusan93

3

在字符串文字前面加上at符号将关闭\转义(在变量前面,它明确地标记变量为非关键字):

Path.Combine(Application.StartupPath, @"CodesLocation\Template.pdf");

Path.Combine 是拼接路径的最先进方法(跨平台,处理额外的斜杆)。


2

您最好使用
Path.Combine(Application.StartupPath, "CodesLocation\\Template.pdf")。 除此之外,请检查Application.StartupPath是否以\结尾。


应用程序的StartupPath不以 \ 结尾,因此仍无法与Path.Combine配合使用。 - kyusan93

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接