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


C# Uri.ToString方法代码示例

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


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

示例1: Execute

        public void Execute(ClientContext ctx, string library, Uri url, string description)
        {
            Logger.Verbose($"Started executing {nameof(AddLinkToLinkList)} for url '{url}' on library '{library}'");

            var web = ctx.Web;
            var links = web.Lists.GetByTitle(library);
            var result = links.GetItems(CamlQuery.CreateAllItemsQuery());

            ctx.Load(result);
            ctx.ExecuteQuery();

            var existingLink =
                result
                    .ToList()
                    .Any(l =>
                    {
                        var u = (FieldUrlValue)l.FieldValues["URL"];
                        return u.Url == url.ToString() && u.Description == description;
                    });

            if (existingLink)
            {
                Logger.Warning($"Link '{url}' with description '{description}' already exists");
                return;
            }

            var newLink = links.AddItem(new ListItemCreationInformation());
            newLink["URL"] = new FieldUrlValue { Url = url.ToString(), Description = description };
            newLink.Update();
            ctx.ExecuteQuery();
        }
开发者ID:ronnieholm,项目名称:Bugfree.Spo.Cqrs,代码行数:31,代码来源:AddLinkToLinkList.cs

示例2: GetSizedImageUrl

        public static string GetSizedImageUrl(Uri ImageUrl, int Width, int Height)
        {
            if (!ImageUrl.IsNullOrEmpty())
            {
                if (!ImageUrl.ToString().Contains("gravatar.com") || !ImageUrl.ToString().Contains("castroller.com"))
                {
                    return String.Format("{0}/{2}/{3}/{1}", Config.SizedBaseUrl, ImageUrl.ToString().Replace("http://", "").Replace("//", "DSLASH"), Width, Height);
                }
                else
                {
                    var min = Math.Min(Width, Height);

                    ImageUrl = new Uri(ImageUrl.ToString().Replace("IMAGESIZE", min.ToString()));

                    int defaultLocation = ImageUrl.ToString().IndexOf("d=");
                    string defaultUrl = ImageUrl.ToString().Substring(defaultLocation + 2);

                    return ImageUrl.ToString().Replace(defaultUrl, HttpUtility.UrlEncode(defaultUrl));

                    //      string noDefault = ImageUrl.ToString().Substring(0, ImageUrl.ToString().IndexOf("&d="));

                    //   return String.Format("{0}&d={1}", noDefault, HttpUtility.UrlEncode(defaultUrl));

                }
            }
            else
            {
                return "";
            }
        }
开发者ID:spaetzel,项目名称:SizedImagesDA,代码行数:30,代码来源:SizedImages.cs

示例3: OnAppLinkRequestReceived

		protected override void OnAppLinkRequestReceived(Uri uri)
		{

			var appDomain = "http://" + AppName.ToLowerInvariant() + "/";

			if (!uri.ToString().ToLowerInvariant().StartsWith(appDomain))
				return;

			var url = uri.ToString().Replace(appDomain, "");

			var parts = url.Split('/');
			if (parts.Length == 2)
			{
				var isPage = parts[0].Trim().ToLower() == "gallery";
				if (isPage)
				{
					string page = parts[1].Trim();
					var pageForms = Activator.CreateInstance(Type.GetType(page));

					var appLinkPageGallery = pageForms as AppLinkPageGallery;
					if (appLinkPageGallery != null)
					{
						appLinkPageGallery.ShowLabel = true;
						(MainPage as MasterDetailPage)?.Detail.Navigation.PushAsync((pageForms as Page));
					}
				}
			}

			base.OnAppLinkRequestReceived(uri);
		}
开发者ID:Costo,项目名称:Xamarin.Forms,代码行数:30,代码来源:App.cs

示例4: GetEntity

        public override Object GetEntity(Uri absoluteUri, string role, Type ofObjectToReturn) {
            if (absoluteUri == null) {
                throw new ArgumentNullException(nameof(absoluteUri));
            }

            if (s_appStreamResolver == null) {
                Debug.Assert(false, "No IApplicationResourceStreamResolver is registered on the XmlXapResolver.");
                throw new XmlException(SR.Xml_InternalError, string.Empty);
            }

            if (ofObjectToReturn == null || ofObjectToReturn == typeof(Stream) || ofObjectToReturn == typeof(Object)) {
                // Note that even though the parameter is called absoluteUri we will only accept
                //   relative Uris here. The base class's ResolveUri can create a relative uri
                //   if no baseUri is specified.
                // Check the argument for common schemes (http, file) and throw exception with nice error message.
                Stream stream;
                try {
                    stream = s_appStreamResolver.GetApplicationResourceStream(absoluteUri);
                }
                catch (ArgumentException e) {
                    throw new XmlException(SR.Xml_XapResolverCannotOpenUri, absoluteUri.ToString(), e, null);
                }
                if (stream == null) {
                    throw new XmlException(SR.Xml_CannotFindFileInXapPackage, absoluteUri.ToString());
                }
                return stream;
            }
            else {
                throw new XmlException(SR.Xml_UnsupportedClass, string.Empty);
            }
        }
开发者ID:Corillian,项目名称:corefx,代码行数:31,代码来源:XmlXapResolver.cs

示例5: Set

 public static void Set(Uri uri)
 {
     if (!Directory.Exists("C:\\WHP\\imgs"))
     {
         Directory.CreateDirectory("C:\\WHP\\imgs");
     }
     string path = uri.ToString().Substring(uri.ToString().LastIndexOf("/") + 1);
     string text = Path.Combine("C:\\WHP\\imgs", path);
     if (!File.Exists(text))
     {
         try
         {
             HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri.ToString());
             httpWebRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.124 Safari/537.36";
             using (Stream responseStream = httpWebRequest.GetResponse().GetResponseStream())
             {
                 using (FileStream fileStream = new FileStream(text, FileMode.Create, FileAccess.ReadWrite))
                 {
                     responseStream.CopyTo(fileStream);
                     fileStream.Flush();
                 }
             }
         }
         catch
         {
             return;
         }
     }
     Wallpaper.SystemParametersInfo(20, 0, text, 3);
 }
开发者ID:v0l,项目名称:whp,代码行数:30,代码来源:Wallpaper.cs

示例6: CreateProxy

 /// <summary>
 /// Create a IWebProxy Object which can be used to access the Internet
 /// This method will check the configuration if the proxy is allowed to be used.
 /// Usages can be found in the DownloadFavIcon or Jira and Confluence plugins
 /// </summary>
 /// <param name="url"></param>
 /// <returns>IWebProxy filled with all the proxy details or null if none is set/wanted</returns>
 public static IWebProxy CreateProxy(Uri uri)
 {
     IWebProxy proxyToUse = null;
     if (config.UseProxy) {
         proxyToUse = WebRequest.DefaultWebProxy;
         if (proxyToUse != null) {
             proxyToUse.Credentials = CredentialCache.DefaultCredentials;
             if (LOG.IsDebugEnabled) {
                 // check the proxy for the Uri
                 if (!proxyToUse.IsBypassed(uri)) {
                     Uri proxyUri = proxyToUse.GetProxy(uri);
                     if (proxyUri != null) {
                         LOG.Debug("Using proxy: " + proxyUri.ToString() + " for " + uri.ToString());
                     } else {
                         LOG.Debug("No proxy found!");
                     }
                 } else {
                     LOG.Debug("Proxy bypass for: " + uri.ToString());
                 }
             }
         } else {
             LOG.Debug("No proxy found!");
         }
     }
     return proxyToUse;
 }
开发者ID:modulexcite,项目名称:ZScreen_Google_Code,代码行数:33,代码来源:NetworkHelper.cs

示例7: getHrefs

        public static void getHrefs(string url)
        {
            // try to fetch href values from a webpage
            try
            {
                // Create an instance of HtmlWeb
                HtmlAgilityPack.HtmlWeb htmlWeb = new HtmlWeb();
                // Creating an instance of HtmlDocument and loading the html source code into it.
                HtmlAgilityPack.HtmlDocument doc = htmlWeb.Load(url);

                // Adding the crawled url to the list of crawled urls
                VisitedPages.Add(url);

                // For each HTML <a> tag found in the document
                foreach (HtmlNode link in doc.DocumentNode.SelectNodes("//a[@href]"))
                {
                    // Extract the href value from the <a> tag
                    Uri l = new Uri(baseUrl, link.Attributes["href"].Value.ToString());

                    // check if the href value does not exist in the list or the queue and if it is a page of the url the user entered.
                    if (!LinkQueue.Contains(l.ToString()) && !VisitedPages.Contains(l.ToString()) && l.Host.ToString() == baseUrl.Host.ToString())
                    {
                        // Add the href value to the queue to get scanned.
                        LinkQueue.Enqueue(l.ToString());
                    }
                }
            }
            catch
            {
                // return if anything goes wrong
                return;
            }
        }
开发者ID:MrBmikhael,项目名称:BasicWebCrawler,代码行数:33,代码来源:Program.cs

示例8: GetUriCookieContainer

       public static CookieContainer GetUriCookieContainer(Uri uri)
       {
            CookieContainer l_Cookies = null;
            // Determine the size of the cookie
            int l_Datasize = 8192 * 16;
            StringBuilder l_CookieData = new StringBuilder(l_Datasize);

            if (!InternetGetCookieEx(uri.ToString(), null, l_CookieData, ref l_Datasize, InternetCookieHttponly, IntPtr.Zero))
            {
                if (l_Datasize < 0)
                    return null;

                // Allocate stringbuilder large enough to hold the cookie
                l_CookieData = new StringBuilder(l_Datasize);

                if (!InternetGetCookieEx(uri.ToString(), null, l_CookieData, ref l_Datasize, InternetCookieHttponly, IntPtr.Zero))
                    return null;
            }

            if (l_CookieData.Length > 0)
            {
                l_Cookies = new CookieContainer();
                l_Cookies.SetCookies(uri, l_CookieData.ToString().Replace(';', ','));
            }
            return l_Cookies;
       }
开发者ID:Jaroski,项目名称:Grepolis2Bot,代码行数:26,代码来源:CookieHelpers.cs

示例9: Navigate

		private static void Navigate(Uri source)
		{
			if (Deployment.Current.Dispatcher.CheckAccess())
				Application.Current.Host.NavigationState = source.ToString();
			else
				Deployment.Current.Dispatcher.InvokeAsync(() => Application.Current.Host.NavigationState = source.ToString());
		}
开发者ID:maurodx,项目名称:ravendb,代码行数:7,代码来源:UrlUtil.cs

示例10: RunClient

        /// <summary>
        /// Runs an HttpClient issuing a POST request against the controller.
        /// </summary>
        static async void RunClient()
        {
            var handler = new HttpClientHandler();
            handler.Credentials = new NetworkCredential("Boris", "xyzxyz");
            var client = new System.Net.Http.HttpClient(handler);

            var bizMsgDTO = new BizMsgDTO
            {
                Name = "Boris",
                Date = DateTime.Now,
                User = "Boris.Momtchev",
            };

            // *** POST/CREATE BizMsg
            Uri address = new Uri(_baseAddress, "/api/BizMsgService");
            HttpResponseMessage response = await client.PostAsJsonAsync(address.ToString(), bizMsgDTO);

            // Check that response was successful or throw exception
            // response.EnsureSuccessStatusCode();

            // BizMsg result = await response.Content.ReadAsAsync<BizMsg>();
            // Console.WriteLine("Result: Name: {0}, Date: {1}, User: {2}, Id: {3}", result.Name, result.Date.ToString(), result.User, result.Id);
            Console.WriteLine(response.StatusCode + " - " + response.Headers.Location);

            // *** PUT/UPDATE BizMsg
            var testID = response.Headers.Location.AbsolutePath.Split('/')[3];
            bizMsgDTO.Name = "Boris Momtchev";
            response = await client.PutAsJsonAsync(address.ToString() + "/" + testID, bizMsgDTO);
            Console.WriteLine(response.StatusCode);

            // *** DELETE BizMsg
            response = await client.DeleteAsync(address.ToString() + "/" + testID);
            Console.WriteLine(response.StatusCode);
        }
开发者ID:BorisMomtchev,项目名称:NiCris.Dashboard-.NET-4.5,代码行数:37,代码来源:Program.cs

示例11: GetElementById

        public virtual SvgElement GetElementById(Uri uri)
        {
            if (uri.ToString().StartsWith("url(")) uri = new Uri(uri.ToString().Substring(4).TrimEnd(')'), UriKind.Relative);
            if (!uri.IsAbsoluteUri && this._document.BaseUri != null && !uri.ToString().StartsWith("#"))
            {
                var fullUri = new Uri(this._document.BaseUri, uri);
                var hash = fullUri.OriginalString.Substring(fullUri.OriginalString.LastIndexOf('#'));
                SvgDocument doc;
                switch (fullUri.Scheme.ToLowerInvariant())
                {
                    case "file":
                        doc = SvgDocument.Open<SvgDocument>(fullUri.LocalPath.Substring(0, fullUri.LocalPath.Length - hash.Length));
                        return doc.IdManager.GetElementById(hash);
                    case "http":
                    case "https":
                        var httpRequest = WebRequest.Create(uri);
                        using (WebResponse webResponse = httpRequest.GetResponse())
                        {
                            doc = SvgDocument.Open<SvgDocument>(webResponse.GetResponseStream());
                            return doc.IdManager.GetElementById(hash);
                        }
                    default:
                        throw new NotSupportedException();
                }

            }
            return this.GetElementById(uri.ToString());
        }
开发者ID:dteunkenstt,项目名称:SVG,代码行数:28,代码来源:SvgElementIdManager.cs

示例12: InitiateAzureADNativeApplicationConnection

        internal static SPOnlineConnection InitiateAzureADNativeApplicationConnection(Uri url, string clientId, Uri redirectUri, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, bool skipAdminCheck = false)
        {
            Core.AuthenticationManager authManager = new Core.AuthenticationManager();


            string appDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            string configFile = Path.Combine(appDataFolder, "OfficeDevPnP.PowerShell\\tokencache.dat");
            FileTokenCache cache = new FileTokenCache(configFile);

            var context = authManager.GetAzureADNativeApplicationAuthenticatedContext(url.ToString(), clientId, redirectUri, cache);

            var connectionType = ConnectionType.OnPrem;
            if (url.Host.ToUpperInvariant().EndsWith("SHAREPOINT.COM"))
            {
                connectionType = ConnectionType.O365;
            }
            if (skipAdminCheck == false)
            {
                if (IsTenantAdminSite(context))
                {
                    connectionType = ConnectionType.TenantAdmin;
                }
            }
            return new SPOnlineConnection(context, connectionType, minimalHealthScore, retryCount, retryWait, null, url.ToString());
        }
开发者ID:sebastienlevert,项目名称:PnP-PowerShell,代码行数:25,代码来源:SPOnlineConnectionHelper.cs

示例13: EncodeUri

        public static string EncodeUri(Uri uri)
        {

            if (!uri.IsAbsoluteUri)
            {
                var uriString = uri.IsWellFormedOriginalString() ? uri.ToString() : Uri.EscapeUriString(uri.ToString());
                return EscapeReservedCspChars(uriString);
            }

            var host = uri.Host;
            var encodedHost = EncodeHostname(host);

            var needsReplacement = !host.Equals(encodedHost);

            var authority = uri.GetLeftPart(UriPartial.Authority);

            if (needsReplacement)
            {
                authority = authority.Replace(host, encodedHost);
            }

            if (uri.PathAndQuery.Equals("/"))
            {
                return authority;
            }

            return authority + EscapeReservedCspChars(uri.PathAndQuery);
        }
开发者ID:modulexcite,项目名称:NWebsec,代码行数:28,代码来源:CspUriSource.cs

示例14: AddParametersToCommand

		public static void AddParametersToCommand(ICommand command, Uri uri)
		{
			try
			{
				NameValueCollection nameValueCollection = HttpUtility.ParseQueryString(uri.Query);
				foreach (string key in nameValueCollection.Keys)
				{
					if (key == null || string.IsNullOrWhiteSpace(key))
					{
						object[] str = new object[1];
						str[0] = uri.ToString();
						throw new DataServiceException(0x190, ExceptionHelpers.GetDataServiceExceptionMessage(HttpStatusCode.BadRequest, Resources.InvalidQueryParameterMessage, str));
					}
					else
					{
						string[] values = nameValueCollection.GetValues(key);
						if ((int)values.Length == 1)
						{
							string str1 = values[0];
							if (!string.IsNullOrWhiteSpace(str1))
							{
								string str2 = key.Trim();
								if (str2.StartsWith("$", StringComparison.OrdinalIgnoreCase))
								{
									continue;
								}
								try
								{
									command.AddParameter(str2, str1.Trim(), true);
								}
								catch (ArgumentException argumentException1)
								{
									ArgumentException argumentException = argumentException1;
									object[] objArray = new object[1];
									objArray[0] = uri.ToString();
									throw new DataServiceException(0x190, string.Empty, ExceptionHelpers.GetDataServiceExceptionMessage(HttpStatusCode.BadRequest, Resources.InvalidQueryParameterMessage, objArray), string.Empty, argumentException);
								}
							}
							else
							{
								object[] objArray1 = new object[1];
								objArray1[0] = uri.ToString();
								throw new DataServiceException(0x190, ExceptionHelpers.GetExceptionMessage(Resources.InvalidQueryParameterMessage, objArray1));
							}
						}
						else
						{
							object[] objArray2 = new object[1];
							objArray2[0] = uri.ToString();
							throw new DataServiceException(0x190, ExceptionHelpers.GetDataServiceExceptionMessage(HttpStatusCode.BadRequest, Resources.InvalidQueryParameterMessage, objArray2));
						}
					}
				}
			}
			catch (Exception exception)
			{
				TraceHelper.Current.UriParsingFailed(uri.ToString());
				throw;
			}
		}
开发者ID:nickchal,项目名称:pash,代码行数:60,代码来源:UriParametersHelper.cs

示例15: Subscribe

        public void Subscribe(Uri address, IEnumerable<string> messageTypes, DateTime? expiration)
        {
            if (address == null || messageTypes == null)
                return;

            using (var tx = NewTransaction())
            using (var session = this.store.OpenSession())
            {
                foreach (var messageType in messageTypes)
                {
                    var type = messageType;

                    var subscription = session.Query<Subscription>()
                        .Where(s => s.Subscriber == address.ToString() && s.MessageType == type)
                        .SingleOrDefault();

                    if (subscription == null)
                    {
                        subscription = new Subscription(address.ToString(), messageType, expiration);
                        session.Store(subscription);
                    }
                    else
                        subscription.Expiration = expiration;
                }
                session.SaveChanges();
                tx.Complete();
            }
        }
开发者ID:codeinpeace,项目名称:NanoMessageBus,代码行数:28,代码来源:RavenSubscriptionStorage.cs


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