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"?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
SDC
  • 249
  • 2
  • 7
  • 14

3 Answers3

20

use this: Uri.AbsolutePath

Request.Url.AbsolutePath
Davide Piras
  • 43,984
  • 10
  • 98
  • 147
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);
competent_tech
  • 44,465
  • 11
  • 90
  • 113
  • this is way more complicated and verbose than what the framework already offers: Request.Url.AbsolutePath – Davide Piras Dec 14 '11 at 20:57
  • 1
    @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. – competent_tech Dec 14 '11 at 21:01
0

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

Hope this helps,

Marvin Smit
  • 4,088
  • 1
  • 22
  • 21