使用服务器文件的路径时,何时需要使用反斜杠或正斜杠(单斜杠或双斜杠)?

时间:2013-01-29 19:48:34

标签: c# asp.net file iis path

关于以下代码示例:

string baseLocation = HttpContext.Current.Server.MapPath("/");
const string templateName = @"//temp//ExportTemplate.xlsx";
const string generatedLocation = @"{0}//temp//{1}";
var fileName = string.Format("Export-{0}.xlsx", DateTime.Now.Date.ToString("yyyy-MM-dd"));
var newFile = String.Format(generatedLocation, baseLocation, fileName);
File.Copy(baseLocation + templateName, newFile, true);

我们在生产服务器和本地开发环境(通过IIS中的站点)上使用它。两者都运行IIS 7.5。代码在生产中正常工作,但在本地开发中引发错误:

Access to the path 'C:\Path\To\Site\//temp//Export-2013-01-29.xlsx' is denied.

在本地开发人员上正确创建/复制文件,但由于路径中的斜杠不正确,我猜测它是错误的。应用程序池标识可以完全访问“临时”标识。文件夹中。

这引出了几个问题:

  • 在这种情况下,' //'路径?我理解' \'是逃避反斜杠的方法,但是' //'没有意义。
  • 两个环境的配置是否存在差异,这使得生成的路径在生产服务器上正常工作但在我的本地开发中失败?

2 个答案:

答案 0 :(得分:2)

代码应使用\,而不是/用于文件路径。 任

const string templateName = @"\temp\ExportTemplate.xlsx";

const string templateName = "\\temp\\ExportTemplate.xlsx";

会正常工作。令人惊讶的是,当前版本的代码在生产中工作,这可能是由于构建的窗口允许文件路径中的正斜杠或反斜杠。 (这可以追溯到DOS时代,当时许多用户也是UNIX用户)

此外,我建议使用Path.Combine而不是仅仅连接文件路径的字符串(这将有助于避免在“C:\ Path \ To \ Site”等路径中获取额外的斜杠或正斜杠\\ TEMP \出口型2013-01-29.xlsx“)。例如:

File.Copy(Path.Combine(baseLocation, templateName), newFile, true);

答案 1 :(得分:0)

//将始终为您提供// ...在字符串处使用@,它是一个逐字字符串文字,您不需要转义字符。因此你可以使用\获取。如果删除@,则需要使用\来获取。使用文件路径时,它始终是反斜杠()。使用URL路径时,它始终是正斜杠(/)