开发者

How to address space in an upload file name

My application could accept upload file with spaces in file names. The problem is when I generate hyperlink to those files, the space within their file names really stopped me from doing this.

DirectoryInfo di = new DirectoryInfo("e:/asdf");
FileInfo[] rgFiles = di.GetFiles("*.*");
if (rgFiles != null)
{
    sb.Append("<span class='SubTitle'>Your attachments list:</span>");
    foreach (FileInfo fi in rgFiles)
    {
       sb.Append("<br><a href=e:\\asdf\\" + fi.Name + ">" + fi.Name + "</a>");
    }
}
else
{
    sb.Append("You don't have any attachment yet.");
}

Shoud I replace all the space to underscore? Well, I don't l开发者_JAVA技巧ike this way. But if I want to add quote to the fi.name it won't display any filenames.


You should put quotes around the entire url:

foreach (FileInfo fi in rgFiles)
{
   sb.Append("<br><a href='e:\\asdf\\" + fi.Name + "'>" + fi.Name + "</a>");
}

This way, if your path has spaces, resulting HTML will look like this:

<br><a href='e:\asdf\your file name.txt'>your file name.txt</a>


Just UrlEncode the filename. It will replace the spaces with valid URL equivalents (%20 or +).

sb.FormatAppend("<br><a href=e:\\asdf\\{0}>{1}</a>", 
                HttpUtility.UrlEncode(fi.Name),
                fi.Name);


Spaces can be represented as %20 in HTML. Try replacing them with that.

But ideally, you should escape the names with an XML/HTML parser.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜