Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
136 views
in Technique[技术] by (71.8m points)

c# - How to encode a path that contains a hash?

How do you properly encode a path that includes a hash (#) in it? Note the hash is not the fragment (bookmark?) indicator but part of the path name.

For example, if there is a path like this:

http://www.contoso.com/code/c#/somecode.cs

It causes problems when you for example try do this:

Uri myUri = new Uri("http://www.contoso.com/code/c#/somecode.cs");

It would seem that it interprets the hash as the fragment indicator.

It feels wrong to manually replace # with %23. Are there other characters that should be replaced? There are some escaping methods in Uri and HttpUtility but none seem to do the trick.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are a few characters you are not supposed to use. You can try to work your way through this very dry documentation, or refer to this handy URL summary on Stack Overflow.

If you check out this very website, you'll see that their C# questions are encoded %23.

Stack Overflow C# Questions

You can do this using either (for ASP.NET):

string.Format("http://www.contoso.com/code/{0}/somecode.cs", 
    Server.UrlEncode("c#")
);

Or for class libraries / desktop:

string.Format("http://www.contoso.com/code/{0}/somecode.cs",
    HttpUtility.UrlEncode("c#")
);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...