Error when replace string with mathematics function name - c#

I have a string: <p><img title="\pi a{^{2}}" src="http://latex.codecogs.com/gif.latex?\pi&space;a{^{2}}" /></p> I want to replace it using base64 string.
Code:
string soalP = file.Path;
string decodeFile = Uri.UnescapeDataString(file.DisplayName);
byte[] imageArray = System.IO.File.ReadAllBytes(soalP);
string base64ImageRepresentation = Convert.ToBase64String(imageArray);
soal = Regex.Replace(soal, "\"http://latex.codecogs.com/gif.latex?" + "\\" + decodeFile + "\"", "data:image/jpeg;base64," + base64ImageRepresentation);
I have a error message:
parsing '"http://latex.codecogs.com/gif.latex?\pi&space;a{^{2}}"' - Malformed \p{X} character escape.
How to handle it?
Note:
I downloaded the picture first and saved it in the local folder.
The file name is encoded file name

Since you are using regular expressions, in the Regex.Replace() method, the second argument is treated as a regular expression for parsing. When there are special characters in the string, it may be mistaken as the symbol resolution of the regular expression, which leads to failure. If you are still confused about the backslash, you can use the string.Replace() method for character substitution.
soal = soal.Replace("\"http://latex.codecogs.com/gif.latex?" + "\\" + decodeFile + "\"", "data:image/jpeg;base64," + base64ImageRepresentation);

Related

Remove \ from end of value

I have the following code:
if (BrowserName.ToUpper().Contains("FIREFOX"))
privateModeParam = " -private-window";
string extraspeech = "\"";
string both = BrowserName + extraspeech + privateModeParam;
Process.Start(both, URLFromDB);
When it run's it returns the following value:
BrowserName = "c:\\program files\\mozilla firefox\\firefox.exe"
both = "c:\\program files\\mozilla firefox\\firefox.exe\" -private-window"
privateModeParam = " -private-window"
What I need to do is, trim the \ from both string because it won't open firefox with that back slash.
I should add if I simply do:
string both = BrowserName + privateModeParam;
the value returned is "c:\program files\mozilla firefox\firefox.exe\ -private-window"
what won't open Firefox
What causes your problems is the double-quote ("), not the back-slash. There is no backslash at this position in the string, it's only displayed like that by your debugger because c# uses \ to escape things like " inside string literals.
So your problem seems to be that you forgot to add extraspeech before the executable, too:
string both = extraspeech + BrowserName + extraspeech + privateModeParam;
or better
string both = $"\"{BrowserName}\" {privateModeParam}"; // C#6
string both = string.Format("\"{0}\" {1}", BrowserName, privateModeParam); // pre C#6
Update:
But the real problem here seems to be that you pass one command line argument in the fileName parameter and one via the arguments parameter.
You should actually call Process.Start like that:
Process.Start(BrowserName, $"{privateModeParam} {URLFromDb}");
Simply pass all arguments in side the arguments parameter. Then there is also no need to wrap the executable in double-quotes as it is the only string in the fileName argument. See documentation for more information about the parameters to Process.Start().
The easiest way would be to use Substring:
MyString = MyString.Substring(0, MyString.Length - 1);
if (BrowserName.EndsWith("\\")){
BrowserName = BrowserName.Substring(0, BrowserName.Length - 1);
}
or
both = both.Replace("\\\"", "");
may fix your problem

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.

Error in opening file having ambersand in the name in asp.net

I have problem in opening file with ambersand in between.
var attachment = "attachment;" + "&test& incident&.txt";
HtmlPage.Window.CreateInstance("foo2", new object[] { Id.ToString(), attachment });
function foo2(theAlert, type) {
alert(type);
window.open('fileViewer.aspx?Id=' + theAlert + '&Type=' + type);
}
When i try to get the type in another page i am getting only the "attachment;" because it taking the words before ampersand. and missing my filename. If i give file name without ampersand i dont have any problem in opening the file.
Any one help me please?
Thanks in advance.
You can use encodeURIComponent
The encodeURIComponent() function encodes a URI component.
This function encodes special characters. In addition, it encodes the
following characters: , / ? : # & = + $ #
window.open('fileViewer.aspx?Id=' + theAlert + '&Type=' + encodeURIComponent(type));
Try the following:
window.open("fileViewer.aspx?Id=" + theAlert + "&Type=" + encodeURIComponent(type));
Changed from encodeURI to encodeURIComponent:
encodeURI is intended for use on the full URI.
encodeURIComponent is intended to be used on .. well .. URI components that is any part that lies between separators (; / ? : # & = + $ , #).

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.

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