【问题标题】:When working with paths to server files, when is it necessary to use back or forward slashes (single or double)?使用服务器文件的路径时,何时需要使用反斜杠或正斜杠(单斜杠或双斜杠)?
【发布时间】:2013-01-29 19:48:34
【问题描述】:

关于以下代码示例:

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.

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

这带来了几个问题:

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

【问题讨论】:

    标签: c# asp.net file iis path


    【解决方案1】:

    代码应该使用 \,而不是 / 作为文件路径。 要么

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

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

    会很好用。令人惊讶的是,当前版本的代码可以在生产环境中运行,这可能是因为 windows 被构建为允许文件路径中的正斜杠或反斜杠。 (这可以追溯到 DOS 时代,当时许多用户也是 UNIX 用户)

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

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2013-07-23
        • 1970-01-01
        • 2015-03-03
        • 1970-01-01
        • 2012-06-16
        • 2010-12-14
        • 1970-01-01
        • 2023-03-16
        相关资源
        最近更新 更多