How to grab .aspx Page Name from the URL? - asp.net

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);

Related

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

Save Xml document in Web-Method in serverpath

How to save XML document in web method in server path in asp.net?
XmlDataDocument doc = new XmlDataDocument(ds);
XmlElement element = doc.DocumentElement;
return ds.GetXml();
string _XMLFileName = HttpContext.Current.Server.MapPath(#"Data\error1.xml");
ds.WriteXml(_XMLFileName);
This should work:
doc.Save(_XMLFileName)
Looking at your comments, can you try using HostingEnvironment.MapPath. Read more on MSDN.
In your case it would be
string _XMLFileName = HostingEnvironment.MapPath("~/App_Data/Data/error1.xml");
HostingEnvironment maps path relative to your hosting location, so you will need to provide ~ for root location. In the example, the file will be inside your root directory of application, under App_Data/Data folder.
Hope this works for you.
This is how I am doing it at the moment..
Dim path As String
path = Server.MapPath("nameOfXMLDoc.xml")
Dim doc As System.Xml.XmlDocument = New System.Xml.XmlDocument()
doc.Load(path)
And it works for me.. found the answer here: http://www.codeproject.com/Articles/165438/Getting-XML-Data-from-Webservice-to-Infopath

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 :)

how to get the full path of file upload control in asp.net?

i am using asp.net 2.0 in my project using file upload control , so browse the drive and select the file like path(D:\user doc new 2011\Montana\MT_SUTA_2010-2011.html)
but in my code seeing error is could not find the file path is
(D:\Paymycheck\OnlineTaxUserDocumentation-1\TaxesDocument\MT_SUTA_2010-2011.html) actually it is application path and take the filename only my code is
if (FileUpload.HasFile)
{
string filepath = Server.MapPath(FileUpload.FileName);
string strHTML = File.ReadAllText(filepath);
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
byte[] file1 = encoding.GetBytes(strHTML);
int len = file1.Length;
byte[] file = new byte[len];
docs.TaxAuthorityName = ddlTaxAuthority.SelectedItem.Text;
docs.TaxTypeID = ddlTaxType.SelectedValue;
docs.TaxTypeDesc = ddlTaxType.SelectedItem.Text;
docs.EffectiveDate = Convert.ToDateTime(txtEffectiveDate.Text);
docs.FileName = f1;
if (ddlTaxAuthority.SelectedValue == "FD")
{
docs.Add(strHTML, file1);
}
}
error occoured in this line
string strHTML = File.ReadAllText(filepath);
i can try like this also
string FolderToSearch = System.IO.Directory.GetParent(FileUpload.PostedFile.FileName).ToString();
string f = Path.GetDirectoryName(FileUpload.PostedFile.FileName);
string f1 = FileUpload.FileName;
string filepath = System.IO.Path.GetFullPath(FileUpload.PostedFile.FileName);
string strFilePath = FileUpload.PostedFile.FileName;
string file1234 = System.IO.Path.GetFullPath(FileUpload.PostedFile.FileName);
string filepath = FileUpload.PostedFile.FileName;
so how to get the total path drive to file
pls help me any one
thank u
hemanth
Because your are using Server.MapPath, which according to MSDN "maps the specified relative or virtual path to the corresponding physical directory on the server." You have to first call FileUpload.SaveAs method to save file on server then try to read it's content.
If you want the total client side drive path like D:\user doc new 2011\Montana\MT_SUTA_2010-2011.html for the file MT_SUTA_2010-2011.html to be uploaded via fileupload control, then try using System.IO.Path.GetFullPath(FileUpload1.PostedFile.FileName).
This will surely return the client side path of the file.
Try this it will work
string filepath = System.IO.Path.GetFullPath(fuldExcel.PostedFile.FileName);
fuldExcel.SaveAs(filepath); //fuldExcel---is my fileupload control ID

Delete files whose filename starts with a certain number

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);

Resources