简体   繁体   中英

Getting Filename from url in C#

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

使用此: Uri.AbsolutePath

Request.Url.AbsolutePath

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);

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

Hope this helps,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM