c# Rich text Format error in code - c#

hoping you can help
I have the following code
List<string> comconfig = populate.resolveconfig(_varibledic, populate.GetVaribles[0].Substring(populate.GetVaribles[0].IndexOf("=") + 1)); //get the aray of strings
string config = ""; //create a empty otput string
config = #"\rtf1\ansi\deff0\deftab240 {\fonttbl {\f000 Monaco;} {\f001 Monaco;} } {\colortbl \red255\green255\blue255; \red000\green000\blue000; \red255\green255\blue255; \red000\green000\blue000; }";
config = config + #"\f96\fs20\cb3\cf2 \highlight1\cf0 "; // assigned rtf header to output string
foreach (var strings in comconfig) //loop though array adding to output string
{
config = config + strings + #"\par ";
}
config = config + "}"; //close of RTF code
So trying to create a RTF string that I can later display. comconfig is an array of strings with some RTF mark up for highlighting and stuff.
trouble is that if I use # then I get double \ which mess up the RTF, and if i dont use them, then the escape charatures mess up the code??
what is the best way to build up this string by adding a preformated RTF header and the aray of strings in the middle. it is displayed finaly in a RTF.textbox. or converted to a plain text string at the users request. I need to ignore the escape charatures with out messing up the RTF?
Cheers
Aaron

No, you don't get a double \. You're getting confuzzled by the debugger display of the string. It shows you what the string looks like if you had written it in C# without the #. Click the spy glass icon at the far right and select the Text Visualizer.

Related

C# Regex Replacement Not Working

I'm trying to remove new lines from a text file. Opening the text file in notepad doesn't reveal the line breaks I'm trying to remove (it looks like one big wall of text), however when I open the file in sublime, I can see them.
In sublime, I can remove the pattern '\n\n' and then the pattern '\n(?!AAD)' no problem. However, when I run the following code, the resulting text file is unchanged:
public void Format(string fileloc)
{
string str = File.ReadAllText(fileloc);
File.WriteAllText(fileloc + "formatted", Regex.Replace(Regex.Replace(str, "\n\n", ""), "\n(?!AAD)", ""));
}
What am I doing wrong?
If you do not want to spend hours trying to re-adjust the code for various types of linebreaks, here is a generic solution:
string str = File.ReadAllText(fileloc);
File.WriteAllText(fileloc + "formatted",
Regex.Replace(Regex.Replace(str, "(?:\r?\n|\r){2}", ""), "(?:\r?\n|\r)(?!AAD)", "")
);
Details:
A linebreak can be matched with (?:\r?\n|\r): an optional CR followed with a single obligatory LF. To match 2 consecutive linebreaks, a limiting quantifier can be appended - (?:\r?\n|\r){2}.
An empirical solution. Opening your sample file in binary mode revealed that it contains 0x0D characters, which are carriage returns \r. So I came up with this (multiple lines for easier debugging):
public void Format(string fileloc)
{
var str = File.ReadAllText(fileloc);
var firstround = Regex.Replace(str, #"\r\r", "");
var secondround = Regex.Replace(firstround, #"\r(?!AAD)", "");
File.WriteAllText(fileloc + "formatted", secondround);
}
Is this possibly a windows/linux mismatch? Try replacing '\r\n' instead.

Replace a string in a text read from a csv and save it

I managed to load the csv and now want to change a few strings inside and then save it again.
First problem: He doesnt want to change the text to '0 . Replacing only "4" with "0" works, but never when my string has more than 1 character.
Second problem: The last replace where I delete all ' to "". When opening the csv in an editor it shows some weird asian characters instead of nothing.
(䈀攀稀甀最猀瀀爀)
There are no spaces in my csv. The csv looks like
.....";"++49 then more random numbers and so on.
This is just the part where ++49 is to be found.
Relevant code:
Encoding ansi = Encoding.GetEncoding(1252);
foreach (string file in Directory.EnumerateFiles(#"path comes here, "*.csv"))
{
string text = File.ReadAllText(file, ansi);
text = text.Replace(#"++49", "'0");
text = text.Replace("+49", "'0");
text = text.Replace(#"""", "");
File.WriteAllText(file, text, ansi);
}
Am i doing something fundamentally wrong?
edit: What it looks like: ";"++49<morenumbers>";; What it should look like: ;0<morenumbers>;;
As people mentioned in comments, problem is with your file encoding decoding. So in this case you can try this:
foreach(string file in Directory.EnumerateFiles(#"path comes here","*.csv"))
{
Encoding ansi;
using (var reader = new System.IO.StreamReader(file, true))
{
ansi = reader.CurrentEncoding; // please tell what you have here ! :)
}
string text = File.ReadAllText(file, ansi);
text = text.Replace(#"++49", "'0");
text = text.Replace(#"+49", "'0");
text = text.Replace(#"""", "");
File.WriteAllText(file, text, ansi);
}
For me it works fine with all formats I was able to set. Then you do not have to set your encoding as hardcoded value

Asp.net, Syntax highlight code from file with google prettify

In my page I will get the ID from link parameters, with that ID I will search the database for the file path, after reading the file and storing its contents I want to put its contents inside my <pre> tag... So I will have a literal in which the text for it will be:
Code.Text = "<pre>" + File Contents in string + "</pre>";
My question is how will I insert the contents there if I need to read the file line by line into an string array, unless I read it all into one string, BUT that will make the text look like one huge line in the page.
Also, is it going to conflict with literal syntax(?) definitions, since for quotes we have to do \" instead of " ...?
If you are working with literal control, you use the StringBiulder And Append properties becouse It let you put any HTML code from code behind.
Something like:
//Declare your String Builder
private StringBuilder stb = new StringBuilder();
And also you could have any proccess when you read the file, and split it by any char like \n
string readFile = //Any Method that you read you file string.
string[] tokens = readFile.Split('\n');
stb.Append("<pre>");
foreach (string s in tokens)
{
stb.Append( s + "<\br>");
}
stb.Append("</pre>");
finally you attach the Stringbuilder value to you Literal
YourLiteral.Text = stb.ToString();
I hope that help, and you won't have the value in one line. And remember the carring return need be in the string file to the split works.
Cheers

How to format the given xml into single line (without spaces)

Using C# how can i format a given xml file into a single single line (without spaces)?
My output is giving symbols if there are spaces and new lines.
Use this:
public static string StripXmlWhitespace(string Xml)
{
Regex Parser = new Regex(#">\s*<");
Xml = Parser.Replace(Xml, "><");
return Xml.Trim();
}
You can use string's Replace method to format xmlString and then save it to output:
string singleLineXml = xml.Replace(System.Environment.NewLine, " ")
or
string singleLineXml = xml.Replace("\r\n", " ")
After removing line breaks > remove spaces:
singleLineXml.Remove(' ');
Yes #Steve Wellens, Remove(' ') is a bad idea.. let's try
singleLineXml.Replace("> <","><");
And i found relative thread, may be it helps Writing string to XML file without formatting (C#)

ASCII raw symbols to control a printer from a .txt file

A label printer is controled by sending a string of raw ASCII characters (which formats a label). Like this:
string s = "\x02L\r" + "D11\r" + "ySWR\r" + "421100001100096" + date + "\r" + "421100002150096" + time + "\r" + "421100001200160" + price + "\r" + "E\r";
RawPrinterHelper.SendStringToPrinter(printerName, s);
This hardcoded variant works well.
Now I want to put the control string to a .txt file and read it during runtime. Like this:
string printstr;
TextReader tr = new StreamReader("print.txt");
printstr = tr.ReadLine();
tr.Close();
But in this case printer prints nothing.
It seems, that StreamReader adds something else to this string
(If I put the read string to a MessageBox.Show(printstr); everything looks OK. Though, this way we can not see control characters added).
What could be a solution to this problem?
Your code calls tr.ReadLine() once, but it looks like you have multiple lines in that string.
Looks like a Zebra label printer, I've had the displeasure. The first thing you need to fix is the way you generate the print.txt file. You'll need to write one line for each section of the command string that's terminated with \r. For example, your command string should be written like this:
printFile.WriteLine("\x02L");
printFile.WriteLine("D11");
printFile.WriteLine("ySWR");
printFile.WriteLine("421100001100096" + date);
printFile.WriteLine("421100002150096" + time);
printFile.WriteLine("421100001200160" + price);
printFile.WriteLine("E");
printFile.WriteLine();
Now you can use ReadLine() when you read the label from print.txt. You'll need to read multiple lines to get the complete label. I added a blank line at the end, you could use that when you read the file to detect that you got all the lines that creates the label. Don't forget to append "\r" again when you send it to the printer.
It could be that the StreamReader is reading it in an Unicode format. By the way, you are reading in only just one line...you need to iterate the lines instead...Your best bet would be to do it this way:
string printstr;
TextReader tr = new StreamReader("print.txt",System.Text.Encoding.ASCII);
printstr = tr.ReadToEnd();
tr.Close();
Or read it as a binary file and read the whole chunk into a series of bytes instead, error checking is omitted.
System.IO.BinaryReader br = new System.IO.BinaryReader(new StreamReader("print.txt", System.Text.Encoding.ASCII));
byte[] data = br.ReadBytes(br.BaseStream.Length);
br.Close();
Edit:
After rem's comment I thought it best to include this additional snippet here...this follows on from the previous snippet where the variable data is referenced...
string sData = System.Text.Encoding.ASCII.GetString(data);
Hope this helps,
Best regards,
Tom.

Categories