9

Currently we have a solution that grabs the filename from the URL using this

currentFile = Path.GetFileNameWithoutExtension(url); 

We found that if there are query strings attached that include characters such as quotes it returns with an error of Illegal characters in path.

For example if the url is

http:\\myurl.com\mypage.aspx?utm_content=This+Is+"Broken" 

Then it won't get the filename. Is there a better, cleaner way to get "mypage"?

5
  • Can't you just remove the query string from the url before calling GetFileNameWithoutExtension? Commented Dec 14, 2011 at 20:39
  • check this one: stackoverflow.com/a/6015377/559144 and vote him up if it solves your issue ;-) Commented Dec 14, 2011 at 20:39
  • did you try Server.UrlEncode(url); before getting the file name ? Commented Dec 14, 2011 at 20:41
  • Possible duplicate: stackoverflow.com/questions/3833680/… Commented Dec 14, 2011 at 20:41
  • Please consider that URLs need not refer to files, and that names with no illegal characters can still be illegal filenames. Commented Dec 14, 2011 at 20:51

3 Answers 3

22

use this: Uri.AbsolutePath

Request.Url.AbsolutePath 
Sign up to request clarification or add additional context in comments.

1 Comment

string filename = Path.GetFileName(new Uri(myUrlString).AbsolutePath);
3

I would just find the ? and if it exists, strip the rest of the string, then use that to GetFileNameWithoutExtension.

For example:

 string url; int index; index = url.IndexOf("?"); if (index != -1) { url = url.Substring(0, index); } currentFile = Path.GetFileNameWithoutExtension(url); 

2 Comments

this is way more complicated and verbose than what the framework already offers: Request.Url.AbsolutePath
@DavidePiras: Why are you assuming that the URL being processed is the request url? The OP made no mention of this in the initial question. The solution I provided was a direct response to their posted code which only referenced a URL. This url could be from a log file, it could be from a referral string, or from a parsed HTML page with embedded references.
0

use HttpContext.Current.Request.PhysicalPath instead of the full URL as parameter into the Path.GetFileNameWithoutExtension method.

Hope this helps,

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.