절대 경로를 다시 웹의 상대 경로
문제
가 있으면을 찾을 수 관리하고의 존재 여부를 확인 파일을 사용하여 서버입니다.MapPath 나는 지금 보내고 싶은 사용자가 직접 하는 파일은 무엇입 가장 빠른 방법을 변환하는 절대 경로로는 상대적인 웹 경로가?
해결책
아마이 작동 수 있습니다:
String RelativePath = AbsolutePath.Replace(Request.ServerVariables["APPL_PHYSICAL_PATH"], String.Empty);
내가 사용하는 c#지만에 적응할 수 있 vb.
다른 팁
지 않을 좋 서버입니다.RelativePath(경로)?
뿐만 아니라,확장해야 합니다;-)
public static class ExtensionMethods
{
public static string RelativePath(this HttpServerUtility srv, string path, HttpRequest context)
{
return path.Replace(context.ServerVariables["APPL_PHYSICAL_PATH"], "~/").Replace(@"\", "/");
}
}
이와 함께 당신은 단순히 call
Server.RelativePath(path, Request);
내가 이것을 알고 있지만 나는 데 필요한 계정한 가상 디렉터리(당@Costo 의 댓글).이는 데 도움이 보인다:
static string RelativeFromAbsolutePath(string path)
{
if(HttpContext.Current != null)
{
var request = HttpContext.Current.Request;
var applicationPath = request.PhysicalApplicationPath;
var virtualDir = request.ApplicationPath;
virtualDir = virtualDir == "/" ? virtualDir : (virtualDir + "/");
return path.Replace(applicationPath, virtualDir).Replace(@"\", "/");
}
throw new InvalidOperationException("We can only map an absolute back to a relative path if an HttpContext is available.");
}
내가 좋아하는 아이디어에서 카노아스.불행하게도 없었"HttpContext.현재 있습니다.요청"사용할 수 있(BundleConfig.cs).
나는 변경 메도 다음과 같다:
public static string RelativePath(this HttpServerUtility srv, string path)
{
return path.Replace(HttpContext.Current.Server.MapPath("~/"), "~/").Replace(@"\", "/");
}
사용한 경우 서버입니다.MapPath,당신은 이미 관계되는 웹 경로입니다.에 따라 MSDN 문서, 이 메소드는 하나의 변수, 경로, 가상의 경로를 웹 서버에 있습니다.그래서 만약 당신이 할 수 있었던 메소드를 호출,당신은 이미 이 상대적인 웹 경로에 즉시 액세스할 수 있습니다.
대 asp.net 핵심 썼는데 도우미 클래스를 테스인들에게 강한 인상을 주었습니다.
public class FilePathHelper
{
private readonly IHostingEnvironment _env;
public FilePathHelper(IHostingEnvironment env)
{
_env = env;
}
public string GetVirtualPath(string physicalPath)
{
if (physicalPath == null) throw new ArgumentException("physicalPath is null");
if (!File.Exists(physicalPath)) throw new FileNotFoundException(physicalPath + " doesn't exists");
var lastWord = _env.WebRootPath.Split("\\").Last();
int relativePathIndex = physicalPath.IndexOf(lastWord) + lastWord.Length;
var relativePath = physicalPath.Substring(relativePathIndex);
return $"/{ relativePath.TrimStart('\\').Replace('\\', '/')}";
}
public string GetPhysicalPath(string relativepath)
{
if (relativepath == null) throw new ArgumentException("relativepath is null");
var fileInfo = _env.WebRootFileProvider.GetFileInfo(relativepath);
if (fileInfo.Exists) return fileInfo.PhysicalPath;
else throw new FileNotFoundException("file doesn't exists");
}
컨트롤러에서 또는 서비스를 삽입 FilePathHelper 사용:
var physicalPath = _fp.GetPhysicalPath("/img/banners/abro.png");
고 반대
var virtualPath = _fp.GetVirtualPath(physicalPath);
제휴하지 않습니다 StackOverflow