我想知道是否有人可以帮助我;
在 PHP 中,您可以使用 fopen(Path) 从文件中读取。路径可以是本地文件(通常格式为 /etc/file 或 c:\file.txt),也可以是 URL,在这种情况下 PHP 将打开 http 连接并从远程位置读取
我想在 VB.Net 中实现同样的目标。我不知道有任何框架功能可以实现这一点。
我目前正在将路径与正则表达式进行模式匹配以获取有效 URL - 如果我得到匹配,我使用 httpwebrequest 打开文件,否则我尝试使用本地文件系统。
这有点 hacky - 我希望找到更好的方法来实现这一点。
任何意见或建议将不胜感激。
Private Function RetrieveBGImage() As Image
Dim Ret As Image
If Not (IsURL(_BackgroundImage) Or IsLocalFile(_BackgroundImage)) Then
Throw New Exception(String.Format("Unable to load from uri ""{0}""", _BackgroundImage))
End If
If IsURL(_BackgroundImage) Then
Dim Response As Net.HttpWebResponse = Nothing
Try
Dim Request As Net.HttpWebRequest = DirectCast(Net.HttpWebRequest.Create(_BackgroundImage), Net.HttpWebRequest)
Response = DirectCast(Request.GetResponse, Net.HttpWebResponse)
Ret = Image.FromStream(Response.GetResponseStream())
Catch ex As Exception
Throw New Exception(String.Format("Unable to load uri: ""{0}"" using HTTPWebRequest. {1}", _BackgroundImage, ex.Message), ex)
Finally
If Response IsNot Nothing Then
Response.Close()
End If
Response = Nothing
End Try
Else
Try
Ret = Image.FromFile(_BackgroundImage)
Catch ex As Exception
Throw New Exception(String.Format("Unable to load uri ""{0}"" using local file system. {1}", _BackgroundImage, ex.Message), ex)
End Try
End If
Return Ret
End Function
Private Function IsURL(ByVal Path As String) As Boolean
Dim RegexObj As New Regex("^(?#Protocol)(?:(?:ht|f)tp(?:s?)\:\/\/|~\/|\/)?(?#Username:Password)(?:\w+:\w+@)?(?#Subdomains)(?:(?:[-\w\d{1-3}]+\.)+(?#TopLevel Domains)(?:com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|edu|co\.uk|ac\.uk|it|fr|tv|museum|asia|local|travel|[a-z]{2})?)(?#Port)(?::[\d]{1,5})?(?#Directories)(?:(?:(?:\/(?:[-\w~!$+|.,=]|%[a-f\d]{2})+)+|\/)+|\?|#)?(?#Query)(?:(?:\?(?:[-\w~!$+|.,*:]|%[a-f\d{2}])+=?(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)(?:&(?:[-\w~!$+|.,*:]|%[a-f\d{2}])+=?(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)*)*(?#Anchor)(?:#(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)?$")
Dim MatchObj As Match = RegexObj.Match(Path)
Return MatchObj.Success
End Function
Private Function IsLocalFile(ByVal Path As String) As Boolean
Dim Ret As Boolean = False
Try
Dim FInfo As New FileInfo(_BackgroundImage)
Ret = FInfo.Exists
Catch handledex As ArgumentException
'Ignore invalid path errors
Catch ex As Exception
Throw New Exception(String.Format("Unable to load uri ""{0}"" using local file system. {1}", Path, ex.Message), ex)
End Try
Return Ret
End Function
注意:我知道上面的逻辑效率低下,实际上最终调用 IsURL() 的次数超过了它必须调用的次数——如果找不到更优雅的解决方案,我打算整理一下。
提前感谢您的帮助