C#路径中的非法字符

时间:2012-05-11 11:51:31

标签: c#

我使用以下代码在路径中收到非法字符:

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

我测试了一些变化:

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

但它仍然会得到同样的非法错误。

任何人都可以帮我看看我的代码是否有错?

感谢。

3 个答案:

答案 0 :(得分:10)

我建议使用适当的方式加入.net中的路径: Path.Combine

所以

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

答案 1 :(得分:2)

字符串文字前面的at会关闭\转义(在变量前面,它明确地将变量标记为而不是关键字):

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

Path.Combine是连接路径的最先进方式(独立于平台,负责额外的削减)。

答案 2 :(得分:2)

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

相关问题