Convert String[] to String need CRLF without using \n\r - c#

We’ve been using Michael Mayer’s Report Printing:
http://www.codeproject.com/Articles/4934/Printing-Reports-in-NET
Yeah, it’s old!
So my problem… We have a Text Box that has Carriage Return and Line Feeds, ex:
THIS
IS
A
TEST
Producing a file to print freezes. I have traced this down to the \r\n in string, ex:
"Mailing Address: 123 Main Street, Wherever, MD 12345\r\n\r\nFacility 1:\r\nProperty Address:”
I know how to do things like split it into a String[] and I can use Regex and Replace and get rid of the \r\n. BUT, ultimately, I want to reconstitute it and have the CRLF, but I can’t use \r\n or Environment.NewLine.
Any thoughts about how I can use this?

I ran into something like this with a project of mine. You can use a function called Replace to replace the characters like this:
myStringWithCRLF.Replace("CRLF", "<---------------New Page-------------->");

I am not 100% sure about the solution, since I never dealt with printing, but maybe it has something to do with encoding?
System.IO.StreamWriter ansiWriter = new StreamWriter("file.txt", false, Encoding.GetEncoding(1250));
This helped me to avoid issues with new lines when I am saving the file.

Related

RichTextBox not showing formfeed character

I have a text file that, when I open it in Notepad, shows the form feed character (byte 12). I want to show this character in my richtextbox but no matter which encoding I use when I read the text file it won't show. When I enter the character myself it shows. When I do myRTB.Text = "♀" it shows, but when I do
myRTB.Text = File.ReadAllText(myFileName.txt);
it doesn't show. I've also tried using the readers in the Encoding class to no avail.
How can I show the form feed character in my rtb?
Firstly, a line feed has a value of 13. If you have characters with the value 12 in there then they are not line feeds.
As for your issue, ReadAllLines reads the lines of a file into a String array, thus stripping out all the line breaks. You might do as Damith suggests and call ReadAllText, which reads the file contents as a single String, and assign the result to the Text property or else call ReadAllLines and assign the result to the Lines property. Better to call LoadFile on the RichTextBox itself though.
try with ReadAllText
myRTB.Text = File.ReadAllText(myFileName.txt, Encoding.Unicode);
Thanks for the help #jmcilhinney and #Damith. I ended up cheating the system by doing a dirty. I saw that myRTB was replacing the form feed char with \page in the RTF, but when I typed the form feed char myself it put \u9792. Therefore I went with the hack:
myRTB.Rtf = myRTB.Rtf.Replace("\\page", "\\u9792");
If you have something less hackish that I can get working please let me know.

How to produce a soft return using C#.net

I know this is kind of easy question but i cant seem to find it anywhere. Is there someone out there who knows how to create a soft return inside a set of text using C#.net?
I need to print soft return to a text file/xml file. this text file will be generated using c#.net. you could verify if the answer is correct if you use NOTEPAD++ then enable the option to “View>Show Symbol > Show End of Line” then you will see a symbol like this:
Thanks in advance :)
Not sure what you mean by a soft return. A quick Google search says it's a non-stored line break typically due to word wrapping in which case you wouldn't actually put this in a string, it would only be relevant when the string was rendered for display.
To put a carriage return and/or line feed in the string you would use:
string s = "line one\r\nline two";
And for further reference, here are the other escape codes that you can use.
Link (MSDN Blogs)
In response to your edit
The LF that you see can be represented with \n in a string. Obviously you have a specific line ending sequence that you need to represent. If you were to use Environment.NewLine that is going to give you different results on different platforms.
var message = $"Tom{Convert.ToChar(10)}Harry";
Results in:
Tom
Harry
With just a line feed between.
Lke already mentioned you can use Enviroment.NewLine but I am not sure if that i what you want or if you are actually trying to append a ASCII 141 to your string as mentioned in the comments.
You can add ASCII chr sequences to your string like this.
var myString = new StringBuilder("Foo");
myString.Append((char)141);

How to read text file between ""

I need an "idea" on how to read text file data between quotes. For example:
line 1: "read a title"
line 2: "read a descr"
line 1: "read a title"
line 2: "read a descr"
I want to do a foreach type of thing, and I want to read all Line 1's, and Line 2's as a pair, but between the ".
In my program I am going to output (foreach of course):
readTerminatedNull(file1);
readTerminatedNull(file2);
I would read line by line, but some of the text could be:
line 1: "read a super long
title that goes off"
line 2: "read a descr"
So that's why I want to read between the ".
Sorry if that is too complicated, and it's a little hard to explain.
Edit:
Thanks for all the feed back guys, but I'm not sure you are getting what I am trying to do :p not your faults, I wrote this kinda wierd.
I will have a text file full of refrences, and text. like so.
text inside:
Refren: "myrefrence_1"
String: "This is a string of a refrence"
Refren: "myrefrence_2"
String: "hello world"
Refren: "myrefrence_3"
String: "I like cookies."
I want it to to read myrefrence_1 in the quotes of the first line, and then read the string in the next line between the ".
I will then stuff into my program that matches the refrence with the string.
But sometimes the text will be more than one line.
Refren: "this is text that goes and then
return keys on some parts."
and I still want it to read through the ".
(not tested, but you'll get the idea)
// Read all text from file
string sData = File.ReadAllText(#"c:/file.txt");
// Match strings between " "
Match match = Regex.Match(sData , "\"(\w|\d|\s|\\\")*\"",
RegexOptions.IgnoreCase);
// Read results and strip " out of them
foreach (var sResult in match) {
sResult = sResult.Remove(0,1).Remove(sResult.length-2, 1);
// Do whatever with sResult
}
You could learn some new tricks by looking into state machines. Basically: Read each character at a time and figure out what state you are in now. First, code this as a big while loop with a big switch statement inside. Then, go and read up on the state pattern for how to do this in an object oriented way. Then, ditch that and use delegates, because c# makes this stuff so easy to do.
Then, scrap it all, write some crappy Regular Expression with a multiline flag and slurp it the Perl way. Meditate on why this is the same as your original state machine solution.
Then, get really stuck in and learn about parser generators (lexx/yacc or some .NET variant) and write a simple BNF grammar for your problem. Take special note of how the trivial grammars used in the tutorials are all way more complicated than the one you need to write. Why is that so? Check out what Noam Chomsky had to say about that.
Eventually, you'll burn out. We all do. But you'll have so much fun digging into what makes programming the coolest activity on the planet. Burn-out is just the realization that that's a pipe dream ;)
When you're done, go outside. Meet people. Talk. Smile a lot. Be friendly. You're now a zen infused developer with a wicked grin. Yay for you! You rock!
What you're describing sounds like a single-column CSV file. The easiest way to access that is probably to use the Microsoft.VisualBasic.FileIO.TextFieldParser class, something like:
using (var csvParser = new TextFieldParser(new StringReader(content))
{
Delimiters = new[] {","},
HasFieldsEnclosedInQuotes = true
})
{
while (!csvParser.EndOfData)
{
var fields = csvParser.ReadFields();
Console.Print(fields[0]); //do something with the first (in your case only) field found.
}
}
Probably the easiest way to determine whether this approach makes sense, is to think about what happens if the string you're reading actually contains a double quote. Would it end up as "He said ""this is quoted"", but I wasn't listening" (doubling up the quotes), or is this situation impossible?
If the quotes would be doubled up in this way, then a standard CSV reader like this built-in framework one is probably your best bet.
To read all of the lines of the file you can use:
File.ReadAllLines(pathToFile);
to strip the text from "" you can use the substring method of string: http://msdn.microsoft.com/en-us/library/aka44szs.aspx
you can do it like that:
string strippedString = original.Substring(1, original.length -2);
Try this one
var text = File.ReadAllLines(pathToFile);
var lines = text.Split(':')
.Where((s,i) => i % 2 != 0)
.Select(s => s.trim('"'));
First of all you need to read in the file using:
File.ReadAllLines(filePath);
Then you could split all the lines using the string.Split function.
Splitting on the closing bracket would be your best bet.
As i have understood from you question is you want to read and write text file with some specific settings. is it ?
I would like to refer to to INI files which are the text files it self and provide the settings configurations as you wish to achieve. here are some links these could help you.
http://www.codeproject.com/Articles/1966/An-INI-file-handling-class-using-C
http://jachman.wordpress.com/2006/09/11/how-to-access-ini-files-in-c-net/

Regex between, from the last to specific end

Today my wish is to take text form the string.
This string must be, between last slash and .partX.rar or .rar
First I tried to find edge's end of the word and then the beginning. After I get that two elements I merged them but I got empty results.
String:
http://hosting.xyz/1234/15-game.part4.rar.html
http://hosting.xyz/1234/16-game.rar.html
Regex:
Begin:(([^/]*)$) - start from last /
End:(.*(?=.part[0-9]+.rar|.rar)) stop before .partX.rar or .rar
As you see, if I merge that codes I won't get any result.
What is more, "end" select me only .partX instead of .partX.rar
All what I want is:
15-game.part4.rar and 16-game.rar
What i tried:
(([^/]*)$)(.*(?=.part[0-9]+.rar|.rar))
(([^/]*)$)
(.*(?=.part[0-9]+.rar|.rar))
I tried also
/[a-zA-Z0-9]+
but I do not know how select symbols.. This could be the easiest way. But this select only letters and numbers, not - or _.
If I could select symbols..
You don't really need a regex for this as you can merely split the url on / and then grab the part of the file name that you need. Since you didn't mention a language, here's an implementation in Perl:
use strict;
use warnings;
my $str1="http://hosting.xyz/1234/15-game.part4.rar.html";
my $str2="http://hosting.xyz/1234/16-game.rar.html";
my $file1=(split(/\//,$str1))[-1]; #last element of the resulting array from splitting on slash
my $file2=(split(/\//,$str2))[-1];
foreach($file1,$file2)
{
s/\.html$//; #for each file name, if it ends in ".html", get rid of that ending.
print "$_\n";
}
The output is:
15-game.part4.rar
16-game.rar
Nothing could be simpler! :-)
Use this:
new Regex("^.*\/(.*)\.html$")
You'll find your filename in the first captured group (don't have a c# compiler at hand, so can't give you working sample, but you have a working regex now! :-) )
See a demo here: http://rubular.com/r/UxFNtJenyF
I'm not a C# coder so can't write full code here but I think you'll need support of negative lookahead here like this:
new Regex("/(?!.*/)(.+?)\.html$");
Matched Group # 1 will have your string i.e. "16-game.rar" OR "15-game.part4.rar"
Use two regexes:
start to substitute .*/ with nothing;
then substitute \.html with nothing.
Job done!

C# Regex Replace

I have a file that is supposed to be \n\n delimited, but of course its not. Some of the lines contains spaces after the \n\n. How do I find a remove all spaces after a \n\n that starts a new line but that is before any other character.
Sample:
\n\nData,Mo re,Data
\n\n Some,Li st,Of
\n\n\nOther,St uff
\n\n\n\n This is another
Desired Output
\n\nData,Mo re,Data
\n\nSome,Li st,Of
\n\nOther,St uff
\n\nThis is another
Regex is probably the answer, but I'm still learning regex. Here's more or less what I've come up with Regex.Replace(input,"^(\n{2,}\s*)", "\n\n") but it doesn't work.
Edit: I should note that I pre-convert from various different line break encodings to \n before this code is needed.
The backslash character needs escaping. Try:
Regex.Replace(input,"^(\n{2,}\\s*)", "\n\n")
Also, you should consider changing \\s* to \\s+ so you don't replace valid line starts unnecesarily.
string test = "\n\nData,Mo re,Data \r\n\n\n Some,Li st,Of \r\n\n\n\nOther,St uff \r\n\n\n\n\n This is another \r\n";
string pattern = "^\n{2,}\\s*";
string result = Regex.Replace(test, pattern, "\n\n", RegexOptions.Multiline);
First, you need the Multiline option. Second, how does your data really look? Notice that where you have a visible cr-lf, I put in \r\n. I did so because you said that it is a \n\n at the beginning of a line that delimits the data. The \n is confusing to work with, so be sure of your data.

Categories

Resources