4

I don't like to post such a general question, but I am not seeing a lot on the topic, so I was wondering if anyone has done something like this, and whether or not this is a good implementation to go with.

EDIT Added whole method

Here is the code

 protected void gridViewAttachments_HtmlDataCellPrepared(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewTableDataCellEventArgs e)
    {
        //if (e.DataColumn.FieldName == "AttachmentName" && e.CellValue.ToString().ToLower().Contains("://"))
        //    attachmentUrl = e.CellValue.ToString();
        //if (e.DataColumn.FieldName == "AttachmentName" && !e.CellValue.ToString().ToLower().Contains("://"))
        //    attachmentUrl = "http://" + e.CellValue;
        Uri targetUri;
        if (Uri.TryCreate("http://" + e.CellValue, UriKind.RelativeOrAbsolute, out targetUri))
        {
            attachmentUrl = new Uri("http://" + e.CellValue);
        }

        if (e.DataColumn is DevExpress.Web.ASPxGridView.GridViewDataHyperLinkColumn)
        {
            if (attachmentUrl.ToString() == "")
            {
                DevExpress.Web.ASPxEditors.Internal.HyperLinkDisplayControl hyperlink =
                    (e.Cell.Controls[0] as DevExpress.Web.ASPxEditors.Internal.HyperLinkDisplayControl);
                hyperlink.Target = "_blank";
                hyperlink.NavigateUrl = ApplicationUrl + "/Attachment.ashx?key=" + hyperlink.Text;
                hyperlink.Text = GetWords("GENERAL.VIEW_ATTACHMENT");
            }
            else
            {
                DevExpress.Web.ASPxEditors.Internal.HyperLinkDisplayControl hyperlink = (e.Cell.Controls[0] as DevExpress.Web.ASPxEditors.Internal.HyperLinkDisplayControl);
                hyperlink.Target = "_blank";

                hyperlink.NavigateUrl = attachmentUrl.ToString();
                hyperlink.Text = "Go to URL";
            }
        }
    }

Pretty basic, and it works. My question is this: Is checking if the string contains :// enough to check whether or not it is a url? The reason I have to check is it is pulling the data from table and some of the fields in the table are filenames (mydoc.docx) in which case I will do something else with them. Is there another more robust check I can do in C#?

4

1 回答 1

8

You could use Uri.TryCreate instead to see if creation of the URL is successful:

Uri targetUri;
if (Uri.TryCreate("http://" + e.CellValue, UriKind.RelativeOrAbsolute, out targetUri))
{
    //success
    attachmentUrl = "http://" + e.CellValue;
}
于 2012-06-04T21:45:59.453 回答