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 :)
Related
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?
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
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
I'm trying to delete all files in a folder which start with a specific user id so if the user id = 00000 then I want to delete file 00000-1.xml & 00000-2.xml & 00000-3.xml and so on.
I have this code so far:
Dim path as String = Server.MapPath("../myfolder/xml/00000" & something?? & ".xml")
If path <> "" Then
Dim fileInfo As FileInfo = Nothing
Try
fileInfo = New FileInfo(path)
If fileInfo.Exists Then
File.Delete(path)
End If
Catch
End Try
End If
Obviously I have just added the something?? in as i have no idea what to put there?
Can anyone shed any light on this?
Consider using Directory.GetFiles instead.
Dim path as String = Server.MapPath("../myfolder/xml")
If path <> "" Then
Dim fileName As String
For Each fileName in Directory.GetFiles (path, "00000-*.xml")
File.Delete(fileName)
Next
End If
You can also just enumerate through any files, if they exist like this (will need to convert to VB syntax):
foreach (string DeleteFileName in Directory.EnumerateFiles(Server.MapPath(#"../MyFolder/xml"), "00000*.xml"))
{
File.Delete(Path.Combine(Server.MapPath(#"../MyFolder/xml"), DeleteFileName));
}
Note, I don't recall offhand whether EnumberateFiles gives just the file name or the fullpath. if fullpath, you can drop the Path.Combine().
Using LINQ:
Directory.EnumerateFiles(Server.MapPath(#"../myfolder/xml", "0000*.abc")).ToList().ForEach(File.Delete);
What object can I use to get the current PageName.aspx (including the extension .aspx) from the URL? I can't find what object and method to allow me to grab this when I'm on a page.
Note that sometimes, on shared hosting like GoDaddy, you might not have the permission to create a new FileInfo object. Yes, believe it.
So I suggest you use this snippet:
string fullPath = /* System.Web.HttpContext.Current. (optional in most cases) */ Request.Url.AbsolutePath;
string fileName = System.IO.Path.GetFileName(fullPath);
Enjoy :-)
Pino here's the source lil man: http://www.devx.com/tips/Tip/42433
string sPagePath = System.Web.HttpContext.Current.Request.Url.AbsolutePath;
System.IO.FileInfo oFileInfo = new System.IO.FileInfo(sPagePath);
string sPageName = oFileInfo.Name;
http://www.aspcode.net/Get-current-page-name.aspx
public string GetCurrentPageName()
{
string sPath = System.Web.HttpContext.Current.Request.Url.AbsolutePath;
System.IO.FileInfo oInfo = new System.IO.FileInfo(sPath);
string sRet = oInfo.Name;
return sRet;
}
Request.Url.AbsolutePath
Split about '/', last item is your file name.
Path.GetFileName(Request.PhysicalPath) can be used to fetch the actual file name
I used: Request.Url.LocalPath, which gave me "/default.aspx", even when full URL would be https://www.example.com/?foo=bar. You just need to strip the leading /.
How about this:
var pageName = System.IO.Path.GetFileName(Request.Url.ToString());
Response.Write(pageName);
string pageName = Path.GetFileName(Request.Path);