Special chars in query string - c#

I am passing a query string parameter containing file name.
default.aspx?file=Fame+ adlabs.xml (Fame+ adlabs.xml is the actual file name on server). The file name has "+" & also blank spaces.
When I check for file name from query string as follows:
var fileName = Request.QueryString["file"];
The variable filename does not have a "+" in it. It reads as "Fame adlabs.xml" & hence I get a file not found exception. I cannot rename the xml files. Can someone please guide me into right direction.
Thanks

If you are trying to do it at the server in C#:
String FileName = "default.aspx?";
String FullURL = FileName + HttpUtility.UrlEncode("Fame + adlabs.xml");
String Decoded = HttpUtility.UrlDecode(FullURL);

You should URL encode into your javascript before sending it :
var name = "Fame+ adlabs.xml";
var url = "default.aspx?file=" + encodeURIComponent(name);
Pay attention that following char won't work : ~!*()'

Related

How to retrieve characters before and after a forward slash

I have this string which comes from the datareader: http://win-167nve0l50/dev/dev/new/1st Account
I want the get the file name, which is "1st Account"
and the list name, which is "new" and the list address which is "http://win-167nve0l50/dev/dev/". This is the code I am using:
How do I retrieve the site address and the list name.
//getting the file URL from the data reader
string fileURL = dataReader["File URL"].ToString();
//getting the list address/path
string listAdd = fileURL.Substring(fileURL.IndexOf("/") + 1);
//getting the file name
string fileName = fileURL.Substring(fileURL.LastIndexOf("/") + 1);
You can get all sorts of info easily using the Uri Class
var uri = new Uri(dataReader["File URL"].ToString());
then you can get various bits from the Uri object eg.
Uri.Authority - Gets the Domain Name System (DNS) host name or IP address and the port number for a server.
Uri.Host - Gets the host component of this instance
Uri.GetLeftPart() - Gets the specified portion of a Uri instance.
If dealing with Uri, use the according class ...
Uri u = new Uri(dataReader["File URL"].ToString());
... and access the desired parts of the path by Segments array
string listAdd = u.Segments[3]; // remove trailing '/' if needed
string fileName = u.Segments[4];
... or in case you need to make sure to handle arbitrary path length
string listAdd = u.Segments[u.Segments.Length - 2];
string fileName = u.Segments[u.Segments.Length - 1];
You should use the Uri class
It's main purpose is to handle composed resource strings.
You can use:
Uri.Host to obtain the host address string
PathAndQuery to getthe absolute path of the file on the server and the query information sent with the request
All the properties here
You can also do it with Regex:
string str = "http://win-167nve0l50/dev/dev/new/1st Account";
Regex reg = new Regex("^(?<address>.*)\\/(?<list>[^\\/]*)\\/(?<file>.*)$");
var match = reg.Match(str);
if (match.Success)
{
string address = match.Groups["address"].Value;
string list = match.Groups["list"].Value;
string file = match.Groups["file"].Value;
}

Remove Extra back slash "\" from string file path in c#

How to convert
"String path = #"C:\Abc\Omg\Why\Me\\\\\\\\\\\\\\\\\\\\\";
into
String path = #"C:\Abc\Omg\Why\Me\".
My approach is to first reverse the string and then remove all the "\" till we get first char, and the reverse it again.
How to do this in C#, is there any method for such operation?
You can just construct path using the Path static class:
string path = Path.GetFullPath(#"C:\Abc\Omg\Why\Me\\\\\\\\\\\\\\\\\\\\\");
After this operation, variable path will contain the minimal version:
C:\Abc\Omg\Why\Me\
You can use path.TrimEnd('\\'). Have a look at the documentation for String.TrimEnd.
If you want the trailing slash, you can add it back easily.
var path = #"C:\Abc\Omg\Why\Me\\\\\\\\\\\\\\\\\\\\\";
path = path.TrimEnd('\\') + '\\';
another solution is
var path = #"C:\Abc\Omg\Why\Me\\\\\\\\\\\\\\\\\\\\\";
path = Path.GetFullPath(path);

Removing file extension in asp.net

How can I remove the extension file in asp.net something like filename.jpg to filename? I tried searching some reference but all I find is URL extension only
Use the System.IO.Path.GetFileNameWithoutExtension Method
The return value for this method is the string returned by GetFileName, minus the last period (.) and all characters following it.
string fileName = Path.GetFileNameWithoutExtension(fuImage.FileName); //file-name
string fileExt = Path.GetExtension(fuImage.FileName); //.jpg,.png....
string path_thumb = Path.Combine("Images/", string.Format("{0}{1}{2}", fileName, "-" + datetime + "-thumb", fileExt)); //full path: Images/file-name-012345-thumb.jpg

If filename has single quote C# javascript does not get executed

I need to pass a URL from C# to javascript. The problem is if the filename has single quote, it does not execute the javascript. When I use HttpUtility.HtmlEncode(fileNameWithoutEx) it does execute javascript but if filename is say "Copy of David's Birth Certificate" then URL gets converted to ?View.aspx?length=60&ext=pdf&file=Copy of David' Birth Certificate.
When View.aspx tries to get the querystring file i.e; filename, it gets set to "Copy of David" and not "Copy of David's Birth Certificate". Because of & it does not get the rest of the querystring.
if (System.IO.File.Exists(fileLocation)) {
string fileNameWithoutExt = System.IO.Path.GetFileNameWithoutExtension(fileLocation);
string fileExtension = System.IO.Path.GetExtension(fileLocation).Replace(".", "");
string title = System.IO.Path.GetFileNameWithoutExtension(fileName);
string url = "View?length=" + 60+ "&ext=" + fileExtension + "&file=" + fileNameWithoutExt;
ScriptManager.RegisterStartupScript(this, GetType(), "ShowPDF", "$(document).ready(function(){ShowPDFDocument('" + title + "', '" + url + "');});", true);
}
How can I send url with single quote to javascript?
What's the best way to handle ' and other special characters?
Use Uri.EscapeDataString(yourLinkHere);. See Uri.EscapeDataString on MSDN.
You're embedding the title and URL within quote-delimited strings in JavaScript, so you need to escape them.
title = title.Replace("'","\\'");
url = url.Replace("'","\\'");
You can try percent codes. I would recommned using %20 in the place of spaces as well. You can chance the file name itself or the way you route to it in code.
urlstring.replace("'", "%27")
Try to replace your ' with %27 which is the standard percent encode for '
Characters with reserved purposes should be replaced to guarantee functionality in all environments. You can view the list and read up on this here.

The given path's format is not supported

I am trying to downlaod an excel sheet and I am dynamically generating its filename which has to be in the following format:
eg:
User_Wise_List_Of_Documents_2013_On_16_04_2013
For this I wrote the following code:
string currentDate = DateTime.Now.Date.ToString();
string currentYear=DateTime.Now.Year.ToString();
filename = Server.MapPath("~/User/Documents/") +
"User_Wise_List_Of_Documents_" + currentYear + "on" + currentDate +
".xls";
Somehow, its giving me the following exception:
The given path's format is not supported.
Any help will be appreciated.
I think your filename contains invalid chars like : Because you are forming filename with string currentDate = DateTime.Now.Date.ToString().
See the list for invalid chars
var invalidChars = Path.GetInvalidFileNameChars();
EDIT
You can use this to replace invalid chars
string newdatestr = String.Join("",currentDate.Select(c => invalidChars.Contains(c) ? '_' : c));
Have you checked the result of Server.MapPath("~/User/Documents/")?
It will return the directory path of your website's folder "/User/Documents/", which would be for example "C:\wwwroot\User\Documents\". You cant download a file from there (unless you're hosting local, in which case it might work, but for you only.
Probably you're looking for the Page.ResolveUrl() function, which will create a web uri relative to your website, rather than to the filesystem.

Categories