当前位置: 首页>>代码示例>>C#>>正文


C# Uri.MakeRelative方法代码示例

本文整理汇总了C#中System.Uri.MakeRelative方法的典型用法代码示例。如果您正苦于以下问题:C# Uri.MakeRelative方法的具体用法?C# Uri.MakeRelative怎么用?C# Uri.MakeRelative使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Uri的用法示例。


在下文中一共展示了Uri.MakeRelative方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: MakeRelative

        //
        // MakeRelative
        //
        //  Return a relative path which when applied to <path1> with a Combine()
        //  results in <path2>
        //
        // Inputs:
        //  <argument>  path1
        //  <argument>  path2
        //      Paths for which we calculate the relative difference
        //
        //  <argument>  compareCase
        //      False if we should consider characters that differ only in case
        //      to be equal
        //
        // Outputs:
        //  Nothing
        //
        // Assumes:
        //  Nothing
        //
        // Returns:
        //  the relative path difference which when applied to <path1> using
        //  Combine(), results in <path2>
        //
        // Throws:
        //  Nothing
        //

        internal static string MakeRelative(string path1, string path2, bool compareCase) {

            Uri u1 = new Uri(path1);
            Uri u2 = new Uri(path2);

            //return PathDifference(path1, path2, compareCase);
            return u1.MakeRelative(u2);
        }
开发者ID:ArildF,项目名称:masters,代码行数:37,代码来源:uri.cs

示例2: GetDisplayName

        /// <summary>
        /// Get display file name from full name.
        /// </summary>
        /// <param name="fullName">Full file name</param>
        /// <returns>Short display name</returns>
        private string GetDisplayName(string fullName)
        {
            // if file is in current directory, show only file name
            //            FileInfo fileInfo = new FileInfo(fullName);
            FileInfo dirInfo=new FileInfo(Directory.GetCurrentDirectory());

            Uri fileUri=new Uri(fullName);
            Uri baseUri=new Uri(dirInfo.FullName+"/null");

            string relativePath=baseUri.MakeRelative(fileUri).Replace('/', '\\');

            if ( relativePath.Length < fullName.Length )
                fullName=relativePath;

            return GetShortDisplayName(fullName, maxDisplayLength);
        }
开发者ID:jugglingcats,项目名称:XEditNet,代码行数:21,代码来源:MRUManager.cs

示例3: MakeRelative

		public void MakeRelative ()
		{
			Uri uri1 = new Uri ("http://www.contoso.com/index.htm?x=2");
			Uri uri2 = new Uri ("http://www.contoso.com/foo/bar/index.htm#fragment");
			Uri uri3 = new Uri ("http://www.contoso.com/bar/foo/index.htm?y=1");
			Uri uri4 = new Uri ("http://www.contoso.com/bar/foo2/index.htm?x=0");
			Uri uri5 = new Uri ("https://www.contoso.com/bar/foo/index.htm?y=1");
			Uri uri6 = new Uri ("http://www.contoso2.com/bar/foo/index.htm?x=0");
			Uri uri7 = new Uri ("http://www.contoso2.com/bar/foo/foobar.htm?z=0&y=5");
			Uri uri8 = new Uri ("http://www.xxx.com/bar/foo/foobar.htm?z=0&y=5" + (char) 0xa9);

			Assert.AreEqual ("foo/bar/index.htm", uri1.MakeRelative (uri2), "#1");
			Assert.AreEqual ("../../index.htm", uri2.MakeRelative (uri1), "#2");

			Assert.AreEqual ("../../bar/foo/index.htm", uri2.MakeRelative (uri3), "#3");
			Assert.AreEqual ("../../foo/bar/index.htm", uri3.MakeRelative (uri2), "#4");

			Assert.AreEqual ("../foo2/index.htm", uri3.MakeRelative (uri4), "#5");
			Assert.AreEqual ("../foo/index.htm", uri4.MakeRelative (uri3), "#6");

			Assert.AreEqual ("https://www.contoso.com/bar/foo/index.htm?y=1", uri4.MakeRelative (uri5), "#7");

			Assert.AreEqual ("http://www.contoso2.com/bar/foo/index.htm?x=0", uri4.MakeRelative (uri6), "#8");

			Assert.AreEqual ("", uri6.MakeRelative (uri6), "#9");
			Assert.AreEqual ("foobar.htm", uri6.MakeRelative (uri7), "#10");

			Uri uri10 = new Uri ("mailto:[email protected]");
			Uri uri11 = new Uri ("mailto:[email protected]?subject=hola");
			Assert.AreEqual ("", uri10.MakeRelative (uri11), "#11");

			Uri uri12 = new Uri ("mailto:[email protected]?subject=hola");
			Assert.AreEqual ("mailto:[email protected]?subject=hola", uri10.MakeRelative (uri12), "#12");

			Uri uri13 = new Uri ("mailto:[email protected]/foo/bar");
			Assert.AreEqual ("/foo/bar", uri10.MakeRelative (uri13), "#13");

			Assert.AreEqual ("http://www.xxx.com/bar/foo/foobar.htm?z=0&y=5" + (char) 0xa9, uri1.MakeRelative (uri8), "#14");
		}
开发者ID:sushihangover,项目名称:playscript,代码行数:39,代码来源:UriTest.cs

示例4: GetPageURL

        private static string GetPageURL(HttpContext context)
        {
            string url = null;
            string currentExecutionFilePath = context.Request.CurrentExecutionFilePath;
            string filePath = context.Request.FilePath;
            if (string.Compare(currentExecutionFilePath, filePath, true) == 0)
            {
                url = currentExecutionFilePath;
            }
            else
            {
                Uri from = new Uri("file://foo" + filePath);
                Uri to = new Uri("file://foo" + currentExecutionFilePath);
#if V2
                url = from.MakeRelativeUri(to).ToString();
#else
                url = from.MakeRelative(to);
#endif
            }
            return url;
        }
开发者ID:katshann,项目名称:ogen,代码行数:21,代码来源:Manager.cs

示例5: HierarchyNode

        /// <include file='doc\Hierarchy.uex' path='docs/doc[@for="HierarchyNode.HierarchyNode2"]/*' />
        /// <summary>
        /// note that here the directorypath needs to end with a backslash...
        /// </summary>
        /// <param name="root"></param>
        /// <param name="type"></param>
        /// <param name="strDirectoryPath"></param>
        public HierarchyNode(Project root, HierarchyNodeType type, string strDirectoryPath){
            Uri uriBase;
            Uri uriNew;
            string relPath;
            // the path is an absolute one, need to make it relative to the project for further use in the xml document
            uriNew = new Uri(strDirectoryPath);
            uriBase = new Uri(root.projFile.BaseURI);
#if WHIDBEY
            relPath = uriBase.MakeRelativeUri(uriNew).ToString();
#else
            relPath = uriBase.MakeRelative(uriNew);
#endif
            relPath = relPath.Replace("/", "\\");

            this.projectMgr = root;
            this.nodeType = type;
            // we need to create an dangling node... just for this abstract folder type
            this.xmlNode = this.projectMgr.projFile.CreateElement("Folder");
            this.xmlNode.SetAttribute("RelPath", relPath);

            this.hierarchyId = this.projectMgr.ItemIdMap.Add(this);
        }
开发者ID:hesam,项目名称:SketchSharp,代码行数:29,代码来源:Hierarchy.cs

示例6: PerformMapping

 public bool PerformMapping(IServiceProvider serviceProvider, IDataObject originalDataObject, DataObject mappedDataObject)
 {
     if (!this.IsValidDataObject(serviceProvider, originalDataObject))
     {
         return false;
     }
     IDocumentDesignerHost service = (IDocumentDesignerHost) serviceProvider.GetService(typeof(IDocumentDesignerHost));
     DocumentProjectItem data = (DocumentProjectItem) originalDataObject.GetData(typeof(ProjectItem).Name);
     bool flag = false;
     if (service == null)
     {
         return flag;
     }
     bool flag2 = false;
     string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(data.Path);
     string fullPath = Path.GetFullPath(data.Path);
     string tagPrefix = string.Empty;
     WebFormsDocument document = service.Document as WebFormsDocument;
     string str4 = Path.GetFullPath(document.DocumentPath);
     if (document == null)
     {
         return flag;
     }
     int num = 0;
     foreach (RegisterDirective directive in document.RegisterDirectives)
     {
         if (!directive.IsUserControl)
         {
             string str5 = directive.TagPrefix;
             if (str5.StartsWith("UC") && !str5.Equals("UC"))
             {
                 try
                 {
                     int num2 = int.Parse(str5.Substring(2));
                     if (num2 >= num)
                     {
                         num = num2 + 1;
                     }
                 }
                 catch
                 {
                 }
             }
             continue;
         }
         if (Path.Combine(str4, directive.SourceFile) == fullPath)
         {
             flag2 = true;
             tagPrefix = directive.TagPrefix;
             fileNameWithoutExtension = directive.TagName;
             break;
         }
     }
     if (!flag2)
     {
         tagPrefix = "uc" + num;
         Uri uri = new Uri(str4);
         Uri toUri = new Uri(fullPath);
         RegisterDirective directive2 = new RegisterDirective(tagPrefix, fileNameWithoutExtension, uri.MakeRelative(toUri), true);
         document.RegisterDirectives.AddRegisterDirective(directive2);
         WebFormsDesignView view = serviceProvider.GetService(typeof(IDesignView)) as WebFormsDesignView;
         if (view != null)
         {
             view.RegisterNamespace(tagPrefix);
         }
     }
     StringBuilder builder = new StringBuilder();
     builder.Append('<');
     builder.Append(tagPrefix);
     builder.Append(':');
     builder.Append(fileNameWithoutExtension);
     builder.Append(" runat=\"server\" />");
     string str6 = builder.ToString();
     mappedDataObject.SetData(DataFormats.Html, str6);
     mappedDataObject.SetData(DataFormats.Text, str6);
     return true;
 }
开发者ID:ikvm,项目名称:webmatrix,代码行数:77,代码来源:UserControlDataObjectMapper.cs

示例7: AddReference

    /// <include file='doc\Project.uex' path='docs/doc[@for="Project.AddReference"]/*' />
    public virtual void AddReference(string name, string path, string projectReference){
      string projectGuid = null;
      if (projectReference != null){
        int rbi = projectReference.IndexOf('}');
        if (rbi > 0){
          projectGuid = projectReference.Substring(0, rbi+1);
        }
      }
      // first check if this guy is already in it...
      foreach (XmlElement f in this.projFile.SelectNodes("//References/Reference")){
        if (projectGuid != null){
          string pguid = f.GetAttribute("Project");
          if (string.Compare(projectGuid, pguid, true, System.Globalization.CultureInfo.InvariantCulture) == 0){
            return;
          }
        }else{
          string file = f.GetAttribute("AssemblyName") + ".dll";

          if (VsShell.IsSamePath(name, file)){
            //TODO: provide a way for an extender to issue a message here
            return;
          }
        }
      }
      // need to insert the reference into the reference list of the project document for persistence
      XmlNode parent = this.projFile.SelectSingleNode("//References");
      XmlElement e = this.projFile.CreateElement("Reference");
      if (projectGuid != null){
        e.SetAttribute("Name", name);
        e.SetAttribute("Project", projectGuid);
        e.SetAttribute("Private", "true");
      }else{
        // extract the assembly name out of the absolute filename
        try{
//          e.SetAttribute("Name", Path.GetFileNameWithoutExtension(name));
          e.SetAttribute("Name", Path.GetFileNameWithoutExtension(path));
        }
        catch {
          e.SetAttribute("Name", name);
        }
        e.SetAttribute("AssemblyName", Path.GetFileNameWithoutExtension(path));
        InitPrivateAttribute(path, e);
        try{
          // create the hint path. If that throws, no harm done....
          string path2 = path.Replace("#","%23");
#if WHIDBEY
          Uri hintURI = new Uri(path2);
          string baseUriString = this.projFile.BaseURI.Replace("#","%23");
          Uri baseURI = new Uri(baseUriString);
          string diff = baseURI.MakeRelativeUri(hintURI).ToString();
#else
          Uri hintURI = new Uri(path2, true);
          string baseUriString = this.projFile.BaseURI.Replace("#","%23");
          Uri baseURI = new Uri(baseUriString, true);
          string diff = baseURI.MakeRelative(hintURI);
#endif
          e.SetAttribute("HintPath", diff);
        } catch{
        }
      }
      parent.AppendChild(e);
      // need to put it into the visual list
      HierarchyNode node = CreateNode(this.projectMgr, HierarchyNodeType.Reference, e);

      // MB - 01/21/05 - leaving this here in case I can find a way to do this.
//      if (projectGuid != null){
//        // For projects in the solution, set a project dependence so the
//        // current project depends on the referenced project.
//        IVsSolution solution = this.Site.GetService(typeof(SVsSolution)) as IVsSolution;
//        object pvar;
//        int i = solution.GetProperty(__VSPROPID_ProjectCount, out pvar);
//      }

      referencesFolder.AddChild(node);
      this.OnAddReferenceNode(node);
    }
开发者ID:dbremner,项目名称:specsharp,代码行数:77,代码来源:Project.cs

示例8: MakeRelative

 /// <summary>
 /// Makes a path relative to a base path.
 /// </summary>
 /// <param name="basePath">The path from which to make a relative path.</param>
 /// <param name="pathToMakeRelative">The path that will be made relative to <paramref name="basePath"/></param>
 /// <returns>The relative path.</returns>
 public static string MakeRelative(string basePath, string pathToMakeRelative)
 {
     Uri baseUri = new Uri(basePath);
     Uri relativeUri = new Uri(pathToMakeRelative);
     #if USE_NET20_FRAMEWORK
     relativeUri = baseUri.MakeRelativeUri(relativeUri);
     string relativePath = relativeUri.ToString();
     #else
     string relativePath = baseUri.MakeRelative(relativeUri);
     #endif
     return relativePath.Replace("/", @"\");
 }
开发者ID:sillsdev,项目名称:FwSupportTools,代码行数:18,代码来源:PackageUtility.cs

示例9: Convert

        public IEnumerable<StaticPageBuilderResponse> Convert(StaticPageConverterRequest request)
        {
            if (request == null) throw new ArgumentNullException("request");
            Contract.EndContractBlock();

            DirectoryInfo requestSourceRoot;
            IEnumerable<FileInfo> sourceFiles;

            var requestSourceFile = new FileInfo(request.Source);
            if (requestSourceFile.Exists)
            {
                requestSourceRoot = requestSourceFile.Directory;
                sourceFiles = new[] { requestSourceFile };
            }
            else
            {
                requestSourceRoot = new DirectoryInfo(request.Source);
                if (requestSourceRoot.Exists)
                {
                    var directories = request.Recursive
                        ? SearchAllDirectories(requestSourceRoot)
                        : new[] { requestSourceRoot };
                    sourceFiles = directories.SelectMany(d => d.EnumerateFiles("*.md"));
                }
                else
                {
                    sourceFiles = Enumerable.Empty<FileInfo>();
                }
            }

            var templateFile = requestSourceRoot.EnumerateFiles("_template.cshtml").FirstOrDefault();
            string razorTemplateCacheKey = null;
            if (templateFile != null && templateFile.Exists)
            {
                razorTemplateCacheKey = templateFile.FullName;
                Razor.Compile(File.ReadAllText(templateFile.FullName), typeof(TemplateModel), razorTemplateCacheKey);
            }

            CommonMarkSettings settings = null;
            var sourceRootUri = new Uri(requestSourceRoot.FullName + Path.DirectorySeparatorChar);
            var results = new List<StaticPageBuilderResponse>();
            foreach (var sourceFile in sourceFiles)
            {
                var localFileUri = new Uri(sourceFile.FullName);
                var relativeSourceFilePath = sourceRootUri.MakeRelative(localFileUri);
                if (Path.DirectorySeparatorChar != '/')
                {
                    relativeSourceFilePath = relativeSourceFilePath.Replace('/', Path.DirectorySeparatorChar);
                }

                var relativeTargetFilePath = Path.ChangeExtension(relativeSourceFilePath, "html");
                var targetFile = new FileInfo(Path.Combine(request.RelativeDestination, relativeTargetFilePath));

                CommonMark.Syntax.Block parsedDocument;
                using (var sourceStream = File.Open(sourceFile.FullName, FileMode.Open, FileAccess.Read, FileShare.Read))
                using (var reader = new StreamReader(sourceStream))
                {
                    parsedDocument = CommonMarkConverter.ProcessStage1(reader, settings);
                }

                CommonMarkConverter.ProcessStage2(parsedDocument, settings);

                if (!targetFile.Directory.Exists)
                {
                    targetFile.Directory.Create();
                }

                using (var targetStream = File.Open(targetFile.FullName, FileMode.Create, FileAccess.ReadWrite, FileShare.None))
                using (var writer = new StreamWriter(targetStream))
                {
                    if (razorTemplateCacheKey != null)
                    {
                        var markdownText = new StringBuilder();
                        using (var markdownWriter = new StringWriter(markdownText))
                        {
                            CommonMarkConverter.ProcessStage3(parsedDocument, markdownWriter, settings);
                        }
                        var htmlResultText = Razor.Run(razorTemplateCacheKey, new TemplateModel{
                            ContentHtml = markdownText.ToString()
                        });
                        writer.Write(htmlResultText);
                    }
                    else
                    {
                        CommonMarkConverter.ProcessStage3(parsedDocument, writer, settings);
                    }
                }

                results.Add(new StaticPageBuilderResponse
                {
                    ResultFile = targetFile
                });
            }

            return results;
        }
开发者ID:aarondandy,项目名称:ducky-docs,代码行数:96,代码来源:StaticPageConverter.cs

示例10: GetRelativeUrl

 protected string GetRelativeUrl(string absoluteUrl)
 {
     if ((absoluteUrl == null) || (absoluteUrl.Length == 0))
     {
         return string.Empty;
     }
     string uriString = absoluteUrl;
     if (this._owner != null)
     {
         string url = this._owner.Url;
         if (url.Length == 0)
         {
             return uriString;
         }
         try
         {
             Uri uri = new Uri(url);
             Uri toUri = new Uri(uriString);
             uriString = uri.MakeRelative(toUri);
         }
         catch
         {
         }
     }
     return uriString;
 }
开发者ID:ikvm,项目名称:webmatrix,代码行数:26,代码来源:Element.cs


注:本文中的System.Uri.MakeRelative方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。