从URI获取本地路径path

本文介绍了一种在Android开发中将Uri转换为本地路径的方法。该方法能够处理两种类型的Uri:一种是通过查询媒体数据库获得路径;另一种是直接从文件型Uri获取路径。

 记录一下Android开发中 Uri转path的方法

/**
 * 从URI获取本地路径
 *
 * @param
 * @return
 */
public static  String getAbsoluteImagePath(Activity activity,Uri contentUri) {

    //如果是对媒体文件,在android开机的时候回去扫描,然后把路径添加到数据库中。
    //由打印的contentUri可以看到:2种结构。正常的是:content://那么这种就要去数据库读取path。
    //另外一种是Uri是 file:///那么这种是 Uri.fromFile(File file);得到的
    System.out.println(contentUri);

    String[] projection = { MediaStore.Images.Media.DATA };
    String urlpath;
    CursorLoader loader = new CursorLoader(activity,contentUri, projection, null, null, null);
    Cursor cursor = loader.loadInBackground();
    try
    {
        int column_index = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        urlpath =cursor.getString(column_index);
        //如果是正常的查询到数据库。然后返回结构
        return urlpath;
    }
    catch (Exception e)
    {

        e.printStackTrace();
        // TODO: handle exception
    }finally{
        if(cursor != null){
            cursor.close();
        }
    }
    //如果是文件。Uri.fromFile(File file)生成的uri。那么下面这个方法可以得到结果
    urlpath = contentUri.getPath();
    return urlpath;
}

 

<think>我们正在讨论的是C#中获取URL的本地路径(即物理路径)的方法。根据引用[1]中的信息,在ASP.NET中可以使用`HttpContext.Current.Request.PhysicalPath`来获取当前页面的完整物理路径。此外,还有其他一些相关的方法可以获取不同情况的路径。 在C#中,获取URL对应的本地路径主要是在Web应用(如ASP.NET)中使用的,因为桌面应用通常不涉及URL路径解析。以下是一些常见的方法: ### 一、在ASP.NET中获取URL的本地路径 #### 1. 获取当前请求页面的物理路径 ```csharp // 获取当前请求页面的物理路径(完整路径) string physicalPath = HttpContext.Current.Request.PhysicalPath; ``` 例如,如果URL是`http://example.com/test/page.aspx`,那么`PhysicalPath`可能是`C:\inetpub\wwwroot\test\page.aspx`(取决于你的网站物理路径)[^1]。 #### 2. 获取当前请求页面的相对路径 ```csharp // 获取当前请求的虚拟路径(如:"/test/page.aspx") string virtualPath = HttpContext.Current.Request.Path; ``` #### 3. 将虚拟路径转换为物理路径 如果你有一个虚拟路径(例如`/images/logo.png`),想将其转换为服务器上的物理路径,可以使用: ```csharp string virtualPath = "/images/logo.png"; string physicalPath = HttpContext.Current.Server.MapPath(virtualPath); ``` 这样,`physicalPath`就会变成类似`C:\inetpub\wwwroot\images\logo.png`的字符串。 ### 二、在ASP.NET Core中获取URL的本地路径 在ASP.NET Core中,由于没有`HttpContext.Current`,我们需要通过依赖注入获取`IWebHostEnvironment`或`HttpContext`。 #### 1. 在控制器中获取 ```csharp public class HomeController : Controller { private readonly IWebHostEnvironment _env; public HomeController(IWebHostEnvironment env) { _env = env; } public IActionResult Index() { // 获取Web根目录的物理路径(如wwwroot) string webRootPath = _env.WebRootPath; // 将虚拟路径转换为物理路径 string virtualPath = "/images/logo.png"; string physicalPath = Path.Combine(webRootPath, virtualPath.TrimStart('/')); // 或者使用Path.Combine直接组合,注意路径分隔符 // 也可以使用以下方法(但ASP.NET Core没有直接的Server.MapPath,通常用WebRootPath或ContentRootPath组合) // 如果是非wwwroot下的文件,可以使用_contentRootPath string contentRootPath = _env.ContentRootPath; // 然后组合路径 string anotherPath = Path.Combine(contentRootPath, "MyData", "data.json"); return View(); } } ``` #### 2. 在Razor页面或视图中 ```csharp @inject IWebHostEnvironment Env @{ string webRootPath = Env.WebRootPath; } ``` ### 三、注意事项 1. **路径安全性**:在处理用户提供的路径时,要防止路径遍历攻击(如`../`)。可以使用`Path.GetFullPath`方法并检查是否在预期目录内。 2. **跨平台**:在Linux或macOS上,路径分隔符是正斜杠`/`,使用`Path.Combine`可以保证正确性。 ### 示例:安全地转换虚拟路径到物理路径 ```csharp public string ConvertToPhysicalPath(string virtualPath) { // 确保虚拟路径以'~/'开头,这是ASP.NET中表示应用程序根目录的约定 if (!virtualPath.StartsWith("~/")) { throw new ArgumentException("虚拟路径必须以~/开头"); } // 替换~为应用程序根目录的虚拟路径 string baseUrl = "/"; // 或者从配置获取 string relativePath = virtualPath.Replace("~", baseUrl).TrimStart('/'); // 组合成物理路径 string physicalPath = Path.Combine(_env.WebRootPath, relativePath); // 规范化路径并检查是否在WebRootPath内 string fullPath = Path.GetFullPath(physicalPath); if (!fullPath.StartsWith(Path.GetFullPath(_env.WebRootPath))) { throw new InvalidOperationException("路径转换后不在Web根目录内"); } return fullPath; } ``` ### 总结 - **ASP.NET (传统)**:使用`HttpContext.Current.Request.PhysicalPath`获取当前页面的物理路径,使用`Server.MapPath`转换虚拟路径。 - **ASP.NET Core**:通过`IWebHostEnvironment`接口获取`WebRootPath`或`ContentRootPath`,然后使用`Path.Combine`组合路径。 --- §§ 相关问题§§ 1. 在C#中如何安全地处理用户上传的文件路径? 2. ASP.NET Core中如何获取应用程序的根目录路径? 3. 如何防止路径遍历攻击(Path Traversal)? 4. 在C#中如何将物理路径转换回URL? 5. ASP.NET Core中的`IWebHostEnvironment`和`IHostEnvironment`有什么区别? </think> 在 C# 中获取 URL 对应的本地路径(物理路径)主要涉及 Web 开发场景,以下是不同技术框架下的实现方法: ### 一、ASP.NET Web Forms (传统) ```csharp // 获取当前请求页面的物理路径 string physicalPath = HttpContext.Current.Request.PhysicalPath; // 将虚拟路径转换为物理路径 string virtualPath = "~/images/logo.png"; string mappedPath = HttpContext.Current.Server.MapPath(virtualPath); ``` > 示例:URL `http://site.com/products/page.aspx` 可能映射到 `C:\inetpub\wwwroot\products\page.aspx` ### 二、ASP.NET MVC / Core #### 方法1:通过 IWebHostEnvironment (推荐) ```csharp // 在控制器中 public class HomeController : Controller { private readonly IWebHostEnvironment _env; public HomeController(IWebHostEnvironment env) { _env = env; } public IActionResult Index() { // 获取Web根目录物理路径 string webRoot = _env.WebRootPath; // 将URL路径转换为物理路径 string imagePath = Path.Combine(webRoot, "assets/img/header.jpg"); return View(); } } ``` #### 方法2:通过 HttpContext ```csharp // 在Razor视图中 @{ string physicalPath = Context.Request.Path; // 获取URL路径 string fullPath = Path.Combine( Environment.ContentRootPath, physicalPath.TrimStart('/') ); } ``` ### 三、通用URL处理方法 ```csharp // 将URL转换为本地路径(适用于文件下载等场景) Uri uri = new Uri("https://example.com/files/report.pdf"); string localPath = Uri.UnescapeDataString(uri.AbsolutePath); // 在Windows环境下调整路径格式 if (Path.DirectorySeparatorChar == '\\') { localPath = localPath.Re('/', Path.DirectorySeparatorChar).TrimStart('\\'); } ``` ### 四、安全注意事项 1. **路径验证**: ```csharp // 防止路径遍历攻击 string safePath = Path.GetFullPath(Path.Combine(baseDir, relativePath)); if (!safePath.StartsWith(baseDir)) { throw new SecurityException("非法路径访问"); } ``` 2. **跨平台处理**: ```csharp // 自动适配操作系统路径分隔符 string crossPlatformPath = Path.Combine( AppContext.BaseDirectory, "content".Replace('/', Path.DirectorySeparatorChar), "data.json" ); ``` ### 五、特殊场景处理 #### 1. 获取网络资源本地缓存路径 ```csharp WebRequest request = WebRequest.Create("https://example.com/image.jpg"); using (WebResponse response = request.GetResponse()) { string tempPath = Path.GetTempFileName(); using (FileStream fs = File.OpenWrite(tempPath)) { response.GetResponseStream().CopyTo(fs); } // 使用 tempPath 操作本地文件 } ``` #### 2. 上传文件到服务器 ```csharp // 根据URL确定存储位置[^3] public void SaveUploadedFile(HttpPostedFile file) { string serverPath = Path.Combine( HttpContext.Current.GetPhysicalPath(), "uploads", Path.GetFileName(file.FileName) ); file.SaveAs(serverPath); } ``` --- **关键点总结**: 1. Web Forms 使用 `Server.MapPath()` 或 `Request.PhysicalPath` 2. ASP.NET Core 使用 `IWebHostEnvironment.WebRootPath` 组合路径 3. 始终使用 `Path.Combine()` 代替字符串拼接 4. 对用户提供的路径进行安全验证 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值