Getting file name from url in C #

We currently have a solution that captures the file name from a URL using this

currentFile = Path.GetFileNameWithoutExtension(url);

We found that if there are query strings that include characters such as quotation marks, they return with an illegal character error in the path.

For example, if the URL

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

Then it will not get the file name. Is there a better, cleaner way to get "mypage"?

+5
source share
3 answers

use this: Uri.AbsolutePath

Request.Url.AbsolutePath
+15
source

I would just find ?, and if it exists, split the rest of the line and then use this for GetFileNameWithoutExtension.

For instance:

        string url;
        int index;

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

HttpContext.Current.Request.PhysicalPath URL- Path.GetFileNameWithoutExtension.

, ,

0

All Articles