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

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.

Related

%u200E appears on my link when i dont want it to appear c#

I have to make a part of my webisite link into arabic language so i have t use leftToRight Char to set the direction of the url but after i used it it placed on the Url %u200E when i dont need it because the url will fail to redirect to my correct path
I used this code it an Example from the internet
string followUpFormula = "FIF";
string renewAbbreviation = "ع.ت" ;
var lefttoright = ((Char)0x200E).ToString();
var result = 10 + "/" + abbreviation + lefttoright + "/" + 2016;
lefttoright is placing %u200E into my url how to avoid placing it on the url ?

Special chars in query string

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 : ~!*()'

Path format is illegal

I want to ask about a easy question , but I faced a problem.
I want to get the time when the program is executed
Console.WriteLine(DateTime.Now);
And I want to output a .log file , the file name will have program execution time
String path2 = "C:\\temp"+DateTime.Now+".log";
StreamWriter path = File.CreateText(path2);
path.WriteLine(DateTime.Now);
But it is telling me Path format is illegal.
And I want ask another question
string a12 = aaa.Element("a12").tostring();
String path2 = "C:\\temp" + a12.ToString + ".log";
But it tell me "Path format is illegal"
How can I resolve it?
Thanks
That's because DateTime.Now converted to string by default contains time information (e.g. 8:53). Semicolon is illegal in path name.
If you meant only date to be in your file name, you could use:
String path2 = "C:\\temp" + DateTime.Now.ToString("d") + ".log";
(Edit) For some cultures this still can lead to invalid values, so as others pointed out, it is best to use explicit formatter:
String path2 = "C:\\temp" + DateTime.Now.ToString("yyyy-MM-dd") + ".log";
You want to escape your \ in the "" quoted string, and also there are characters in the result of DateTime.Now that cannot be in paths. You'll need to escape/replace those as well.
When you put DateTime.Now into a path, you risk adding characters that aren't valid as a path (like the : separator. That is the reason you get this error message.
You could replace it with a .:
string path2 = Path.Combine
( #"C:\temp\"
, DateTime.Now.ToString("yyyy-MM-dd.HH24.mm.ss")
, ".log"
);
DateTime.Now probably contains illegal characters depending on your local system settings. To get a valid and consistent file name independent on the culture the system is installed in you should create the log file name by hand, for instance like this:
String path2 = "C:\\temp" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".log";
String path2 = String.Format("C:\\temp{0}.log", DateTime.Now.ToString("yyyyMMdd"));
Since filename cannot take "/" which was created by DateTime.Now.ToString("d") and hence creating issue.

C# removes backslash '\' from a string

I am creating a PDF file on a windows temporary directory with this method:
System.IO.Path.GetTempPath()
and also I'm concatenating a the string with a DateTime like this code:
string pathPdf = string.Format(System.IO.Path.GetTempPath() + "detalle-{0}{1:yyyyMMddhhmmss}.pdf", txtFolio_detalle_consum.Text, DateTime.Now);
this is the value of the string:
C:\\Users\\Admin\\AppData\\Local\\Temp\\detalle-6020121112102343.pdf
But when I try to use the value later in the code some how c# removes me the doubel backslash ending the string in the following way:
C:UsersAdminAppDataLocalTempdetalle-6020121112102343.pdf
without the backslashes.
Any one have an Idea of why c# is doing this?
Thanks in advance.
UPDATE
I output the variables with a Javascript alert using the following function:
protected void alerta(string msj)
{
string script1 = #"<script type='text/javascript'>alert('" + msj + "');</script>";
ScriptManager.RegisterStartupScript(this, typeof(Page), "Adv", script1, false);
}
I'm also passing this variable to use it on a query string like this:
string scriptjs = string.Format("<script language='JavaScript'>window.open('emergentes_consum/vista_previa_imprimir.aspx?DocumentUrl={0}', '_blank', 'fullscreen=no')</script>",pathPdf);
ScriptManager.RegisterStartupScript(this, typeof(Page), "Capturar_Emails", scriptjs, false);
Launch the debugger, add the variable to your Watch window and go step by step through your program to find the code that removes these slashes. C# does not do that by itself.
Side note - use System.IO.Path.Combine to concatenate paths (folders and files).
As it turned out in the comments, the string in question was passed to JavaScript alert - so the solution was to add a call to HttpUtility.JavaScriptStringEncode
That is not the value of the string.
That's how the debugger displays the string.
If you write a string literal in source code, you need to escape the \s, or use a verbatim string literal (#"C:\a\b")

String concatenation doesn't seem to work in C#

I don't know what is wrong with the following string:
"Report(" + System.DateTime.Now.ToString("dd-MMM-yyyy") + " to " + System.DateTime.Now.AddMonths(-1).ToString("dd-MMM-yyyy") + ")"
I can't get the concatenated string. I am getting Report(29-Dec-2009. That's all and
the rest gets left out from the string.
What is the reason?
Try this:
string filename =
String.Format(
"Report({0:dd-MMM-yyyy} to {1:dd-MMM-yyyy})",
System.DateTime.Now, System.DateTime.Now.AddMonths(-1));
EDIT: Since in your download box you got your filename broken in first whitespace, you could to try ONE of these:
filename = HttpUtility.UrlEncode(filename); // OR
filename = """" + filename + """";
Seems some browsers doesn't handles whitespaces very nicely: Filenames with spaces are truncated upon download. Please check it you can to download other filenames with whitespace in other sites.
You need to assign it to something:
string s = "Report(" + System.DateTime.Now.ToString("dd-MMM-yyyy") + " to " + System.DateTime.Now.AddMonths(-1).ToString("dd-MMM-yyyy") + ")"
Update: I just saw your update to the question. How are you displaying the string? I'm guessing that you are displaying it in a GUI and the label is too short to display the complete text.
Try this:
string newstring =
string.Format(
"Report ({0} to {1})",
System.DateTime.Now.ToString("dd-MMM-yyyy"),
System.DateTime.Now.AddMonths(-1).ToString("dd-MMM-yyyy")
);
What are you assigning the result to? It would be easier to read the code if you used string.Format
You are not assigning the concatenated result to anything, so can't use it:
string myConcatenated = "Report(" + System.DateTime.Now.ToString("dd-MMM-yyyy") + ")";
Using this code...
string test = "Report(" + System.DateTime.Now.ToString("dd-MMM-yyyy") + " to " +
System.DateTime.Now.AddMonths(-1).ToString("dd-MMM-yyyy") + ")";
I saw the following result.
Report(29-Dec-2009 to 29-Nov-2009)
It could be that the string is being truncated later on. Make sure that you set a breakpoint right after this code is run and check the value of the variable to which it is assigned (test in my case).
If, as in your previous question, you are using this value to create a file, it may be that it's the space before "to" that is causing the problem. Try to use:
"Report("
+ System.DateTime.Now.ToString("dd-MMM-yyyy")
+ "To"
+ System.DateTime.Now.AddMonths(-1).ToString("dd-MMM-yyyy")
+ ")"
instead and see if that fixes it.
If that does fix it, you'll probably need to either figure out how to quote the entire file name so it's not treated as the three separate arguments, "Report(29-Dec-2009", "to" and "29-Nov-2009)". Or simply leave your reports names without spaces.
I'd choose the latter but then I'm fundamentally opposed to spaces in filenames - they make simple scripts so much harder to write :-)

Categories