Why won't File.copy work with Server.MapPath - asp.net

I'm trying to do something really simple but its taking longer to figure out than it should.
So I have this copy method which works where both the source file and destination are string values.
Hard coded values work
Dim copyPath As String ="C:\inetpub\wwwroot\somesite.com\someFolder\dink1\muffin.gif"
Dim copyPath2 As String = C:\inetpub\wwwroot\somesite.com\someFolder\dink2\muffin.gif"
File.Copy(copyPath, copyPath2)
But this doesn't work
Dim copyPath As String = Server.MapPath("~/someFolder/dink1/" + fileName)
Dim copyPath2 As String = Server.MapPath("~/someFolder/dink2/" + fileName)
File.Copy(copyPath, copyPath2)
What do I need to do to properly build out the paths here?

Server.MapPath is a secure method, and requires that you have AspEnableParentPaths set to true for your application.
http://msdn.microsoft.com/en-us/library/ms524632(v=vs.90).aspx

Related

string.split()(1) removes first character

I am running into an issue when i split a string on "_Pub" and get the back half of the string it removes the first character and I don't understand why or how to fix it unless i add the character back in
strFilePath = "/C:/Dev/Edge/_Publications/Ann Report/2013-2016/2016 Edge.pdf"
Dim relPath = strFilepath.Split("_Publications")(1)
lb.CommandArgument = relPath
returns Publications\Ann Report\2013-2016\2016 Edge.pdf
What you have as a delimiter is not a string array "string()" but a regular string. You need a string array to use a string as a delimiter. otherwise it takes the first char of your string.
https://msdn.microsoft.com/en-us/library/tabh47cf(v=vs.110).aspx
try this
Dim relPath = strFilepath.Split(new string() {"_Publications"}, StringSplitOptions.RemoveEmptyEntries)(1)
It appears that you want to get the part of the path starting at some directory. Splitting the path might not be such a good idea: imagine if there was a file "My_Publications_2017.pdf" in a directory "C:\Dev\Edge\_Publications". The split as you intended in the question would give the array of strings {"C:\Dev\Edge\", "\My", "_2017.pdf"}. As has been pointed out elsewhere, the String.Split you used doesn't do that anyway.
A more robust way would be to find where the starting directory's name is in the full path and get the substring of the path starting with it, e.g.:
Function GetRelativePath(fullPath As String, startingDirectory As String) As String
' Fix some errors in how the fullPath might be supplied:
Dim tidiedPath = Path.GetFullPath(fullPath.TrimStart("/".ToCharArray()))
Dim sep = Path.DirectorySeparatorChar
Dim pathRoot = sep & startingDirectory.Trim(New Char() {sep}) & sep
Dim i = tidiedPath.IndexOf(pathRoot)
If i < 0 Then
Throw New DirectoryNotFoundException($"Cannot find {pathRoot} in {fullPath}.")
End If
' There will be a DirectorySeparatorChar at the start - do not include it
Return tidiedPath.Substring(i + 1)
End Function
So,
Dim s = "/C:/Dev/Edge/_Publications/Ann Report/2013-2016/2016 Edge.pdf"
Console.WriteLine(GetRelativePath(s, "_Publications"))
Console.WriteLine(GetRelativePath(s, "\Ann Report"))
outputs:
_Publications\Ann Report\2013-2016\2016 Edge.pdf
Ann Report\2013-2016\2016 Edge.pdf
Guessing that you might have several malformed paths starting with a "/" and using "/" as the directory separator character instead of "\", I put some code in to mitigate those problems.
The Split() function is supposed to exclude the entire delimiter from the result. Could you re-check & confirm your input and output strings?

Getting UserAgent from code in a DLL

The necessary references to System.Web and the Impports statement are already in the DLL
In code behind you can do this:
Dim MyString As String = Request.UserAgent
but transfer that code into a DLL and it's no good. I cannot seem to define ServerVariables("HTTP_USER_AGENT") either.
I have even tried this
Dim wr As System.Web.HttpRequest = New Web.HttpRequest(Nothing, Nothing, Nothing)
Dim s As String = wr.UserAgent
but get an error Object Not Set... If I add a URL for the middle value as I don't require a Filename or a QueryString, no luck either.
Dim wr As System.Web.HttpRequest = New Web.HttpRequest(Nothing, "https://stackoverflow.com", Nothing)
Dim s As String = wr.UserAgent
How can I return the visitors UserAgent using code from a DLL an NOT Code Behind, please? I have checked for this answer on this site and couldn't find one.
When outside of code-behind you can do this:
Dim MyString As String = HttpContext.Current.Request.UserAgent
HttpContext.Current also has properties for Response, Server, Session, and plenty of other useful values.

Using ParseQueryString function to get values from QueryString

I needed to get values out of a string in a QueryString format, that is such as: data1=value1&data2=value2...
Someone suggested I used HttpUtility.ParseQueryString to get the value, I've searched and searched but I can't find any documentation or implementation of this and the Microsoft documentation for it doesn't explain how it works, can someone tell me hwat I'm doing wrong, my code is below;
Public Shared Sub ProcessString(ByVal Vstring As String)
Dim var As NameValueCollection = HttpUtility.ParseQueryString(Vstring)
Dim vname As String = var.QueryString("VNAME")
End Sub
MSDN has an example.
' Parse the query string variables into a NameValueCollection.
Dim qscoll As System.Collections.Specialized.NameValueCollection = HttpUtility.ParseQueryString(Vstring)
Dim vname As String = qscoll("VNAME")
A NameValueCollection represents a collection of associated String keys and String values that can be accessed either with the key or with the index.
I found the problem, I was referencing everything fine but I was doing it in a separate .VB dependency file, once I did it on the actual code behind of the aspx form that solved the problem and it all worked. So now I'm just passing the string from Codebehind as a specialised.NameValue collection in to the function.

How to call a node from a xml file within asp.net web page

I am trying to use the value of <Directory> in my following piece of code:
Public Function GetFile() As String
Dim di As New DirectoryInfo(< Directory >)
Dim files As FileSystemInfo() = di.GetFileSystemInfos()
Dim newestFile = files.OrderByDescending(Function(f) f.CreationTime).First
Return newestFile.FullName
End Function
Is there any way i can call the value stored in the xml file in my code?
Andy's answer is good, but in VB it's even easier.
Dim xmlDoc As XDocument
Dim dir as String
xmlDoc = XDocument.Load("XMLFile1.xml")
dir = xmlDoc.<ServerList>.<Server>.<Directory>.First().Value;
Or even easier if the XML file will never have more than one <Directory> element that you care about:
dir = xmlDoc...<Directory>.First().Value;
To answer your comment on Andy's answer:
dir = (From server as XElement in xmlDoc...<Server>
Where server.<ServerName>.First().Value = requiredServer
Select server.<Directory>.First().Value)(0);
As you are clearly familiar with Linq, you can operate on the Xml using System.Xml.Linq.
Apologies, this is in c#.
var xDoc = XDocument.Load("XMLFile1.xml");
var dir = xDoc.Element("ServerList").Elements("Server").Elements("Directory").First().Value;
If you have the Xml stored in a string replace XDocument.Load with XDocument.Parse.
Obviously you'll have to defend against parse errors, file missing and schema inconsistencies in your production code.
You can use this http://support.microsoft.com/kb/301225

VB.net / asp.net: Get URL without filename

i want to set a link in VB.net dynamically to a file.
My url looks like that:
http://server/folder/folder2/file.aspx?get=param
I tried to use Request.URL but i have not found any solution to get only
http://server/folder/folder2/
without the query string and without the filename.
Please help.
Dim url = Request.Url;
Dim result = String.Format(
"{0}{1}",
url.GetLeftPart(UriPartial.Authority),
String.Join(string.Empty, url.Segments.Take(url.Segments.Length - 1))
)
You can easily get a relative file path using the Request instance, then work with that, using Path class ought to help:
Dim relativePath = Request.AppRelativeCurrentExecutionFilePath
Dim relativeDirectoryPath = System.IO.Path.GetDirectoryName(relativePath)
It's worth noting that GetDirectoryName might transform your slashes, so you could expand the path:
Dim mappedPath = HttpContext.Current.Server.MapPath(newpath)
So, to remove redundancy, we could shorten this:
Dim path = _
Server.MapPath( _
Path.GetDirectoryName( _
Request.AppRelativeCurrentExecutionFilePath)))
But you'll need to check for possible exceptions.
You can use Uri.Host to get the computer name and then Uri.Segments (an array) to get everything up to the filename, for example:
var fileName = Uri.Host && Uri.Segments(0) && Uri.Segments(1)
This will give you: server/folder/folder2
If you have a variable number of segments, you can iterate over them and ignore the last one.
I hope that might help :)

Resources