zoukankan      html  css  js  c++  java
  • ASP.NET中关于路径(Path)的相关知识

    也许你曾遇到过这样的情况
    运行类似的代码
    StreamReader sr=new StreamReader("Test.txt");
    运行时会提示:"Could not find file 'C:"windows"system32"Test.txt".
    这就是路径不对造成的
    幸好在asp.net的request对象中有许多与路径相关的属性

    ApplicationPath 程序的虚拟根目录路径
    CurrentExecutionFilePath 当前请求的虚拟路径
    FilePath
    Path
    PathInfo
    PhysicalApplicationPath 程序虚拟根目录的物理路径
    PhysicalPath 请求URL的物理路径
    RawUrl 当前请求的原始URL
    Url 当前请求的URL信息

    例如 如果我有一个名为ASPNETC的网站 它是我网站根目录下的一个子目录C:\Webs
    输出如下:
    ApplicationPath: "/"
    CurrentExecutionFilePath: /aspnetc/testpath.aspx
    FilePath: /aspnetc/testpath.aspx
    Path: /aspnetc/testpath.aspx
    PathInfo:
    PhysicalApplicationPath: C:\webs\
    PhysicalPath: C:\webs\aspnetc\testpath.aspx
    RawUrl: /aspnetc/testpath.aspx

    RawUrl包含QueryString信息 PathInfo可以用来Url重写

    非常有用的 "~" and Page.ResolveUrl 两者结合起来能很方便的获取路径
    "~"代表当前应用程序的根目录,经常在控件中使用,用来定位图片,css等文件的位置。
    如果应用程序搬家了,放到不同的根目录下面,则会出现问题
    Page的ResolveUrl正是用来解决这个问题

    如果你的程序在"/SomeDir"
    Page.ResolveUrl("~/images/image1.jpg") 返回 "/Somedir/images/image1.jpg"
    在根目录
    Page.ResolveUrl("~/images/image1.jpg") will simply return "/images/image1.jpg"

    Server.MapPath方法相关
    Server.MapPath("/") Server.MapPath("~")得到当前应用程序根目录的物理路径
    Server.MapPath(".")得到当前目录的物理路径
    Server.MapPath("..")得到父目录的物理路径

    用Path.Combine连接路径
    //Returns C:"testdir"images"image1.jpg
    Path.Combine(@"C:"testdir", @"Images"image1.jpg");

    NET中Path类的几个方法

    1. Path.combine(string, string)
         根据给出的两个路径, 返回一个路径.
          例如:

         string CompletePath = System.IO.Path.Combine(@"c:\MyApp", @"Images\skyline.jpg");
         将会返回一个全路径 c:\MyApp\Images\skyline.jpg
         第一个参数中有无"\"结尾都可以.

    2. Path.GetExtension(string)
        返回给定文件路径的扩展名.例如:
    string FileExtention = System.IO.Path.GetExtention(@"C:\MyApp\Images\skyline.jpg");
        将会返回 "jpg"

    3. Path.GetFileName(string)
         给出文件名的全路径,返回文件名(包括扩展名).例如:
    string fileName = System.IO.Path.GetFileName(@"c:\MyApp\Images\skyline.jpg");
        将会返回"skyline.jpg"
  • 相关阅读:
    html禁止手机页面放大缩小
    <httpProtocol/>配置http协议头
    C# 并行编程 之 并发集合 (.Net Framework 4.0)(转)
    JavaScript随机排序算法1
    用户消息处理方式
    后台单用户在线,简单处理
    使用 Intel HAXM 为 Android 模拟器加速,媲美真机(转)
    解决Android SDK Manager下载太慢问题(转)
    如何正确并完全安装Visual Studio 2015企业版本?(转)
    C# XML流操作简单实例
  • 原文地址:https://www.cnblogs.com/purplefox2008/p/1729019.html
Copyright © 2011-2022 走看看