当路径服务器上的文件工作,什么时候需要使用背面或正斜杠(单人或双人)? [英] When working with paths to server files, when is it necessary to use back or forward slashes (single or double)?

查看:88
本文介绍了当路径服务器上的文件工作,什么时候需要使用背面或正斜杠(单人或双人)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关以下code样品:<​​/ P>

Regarding the following code sample:

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。在code工作正常生产,但抛出本地开发的错误:

We are using this on a production server and a local dev environment (via a site in IIS). Both are running IIS 7.5. The code works correctly on production, but throws an error in local dev:

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

该文件被创建/在本地开发正确复制,但我猜测它的示数出由于路径是不正确的斜杠。该应用程序池标识已经完全进入了临时文件夹中。

The file is created/copied correctly on local dev, but I'm guessing it's erroring out due to the slashes in the path being incorrect. The app pool identity has full access to the 'temp' folder.

这带来了两个问题:


  • 在这种情况下,什么是'//'做路径?我明白了'\\'是逃避反斜杠的方式,但在'//'是没有意义的。

  • 莫不是在正确使得生产服务器上生成的路径工作两个环境的配置有差别,但在我的本地开发失败?

推荐答案

在code应该使用\\,而不是/文件路径。
无论

The code should be using a \, not / for file paths. Either

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

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

将正常工作。这是令人惊讶的生产code ++工程的当前版本,这可能是由于Windows正在建立允许向前或向后斜线在文件路径。 (这可以追溯到DOS时代,当许多用户也UNIX用户)

would work fine. It's surprising the current version of the code works in production,it may be due to that windows is built to allow either forward or back slashes in file paths. (this goes back to DOS days when many of the users were also UNIX users)

另外,我推荐使用 Path.Combine ,而不是仅仅串联的字符串的文件路径(这将得到帮助避免让多余的斜线或向前斜杠像路径C:\\路径\\为\\网站\\\\ TEMP \\出口为主2013-01-29.xlsx)。例如:

In addition, I'd recommend using Path.Combine rather than just concatenating the strings for the file path (this will get help avoid getting extra slashes or forward slashes in paths like "C:\Path\To\Site\\temp\Export-2013-01-29.xlsx"). ex:

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

这篇关于当路径服务器上的文件工作,什么时候需要使用背面或正斜杠(单人或双人)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆