Indent only in second line in paragraph in rich text box (c#) - c#

How can I make indent only in the second row, to be space under the first word of paragraph.
as this:

If you can read each line into an array, loop through that array, and if index = 1 then add "\t" to the beginning of the line then adding it to the output String. Let's see if I can write up an example.
Let's say you already read each line into String[] lines.
String[] lines = readFromTextFileLineByLine();
String output = "";
int index = 0;
foreach(String line in lines)
{
if(index==1)
line = "\t" + line;
output += line;
index++;
}
I hope this helps.
Now for each paragraph in a richtextbox would be a bit different. Maybe you can split the text up by "\n", instead of reading from a file line by line, then running this to change your output. You will, however, run into the issue of where a new line occurs and how large the text box is width wise.

Related

How to add text to the line that starts with "hello" in a file

I have a file that contains many lines. There is a line here looking like below:
hello jim jack nina richi sam
I need to add a specific text salmon in this line and change it to below (it could be added anywhere in this line -end -begining - in the middle -doesnt matter ):
hello jim jack nina richi sam salmon
I tried:
string path = #"C:\testFolder\newTestLog.txt";
StreamReader myReader = new StreamReader(path);
string[] allLines = File.ReadAllLines(path);
foreach (string element in allLines) {
if (element.StartsWith("hello"))
{
Console.WriteLine(element);
}
}
myReader.Close();
}
Using this I'm able to read the file line by line and add each line to an array and print that line if that starts with "hello", but I'm not sure how to add text to this line
You should use what Joel answered it's nicer but if you're having trouble implementing it try this. After adding the salmon to the lines that start with hello you can overwrite the txt file by using File.WriteAllLines
string filePath = #"C:\testFolder\newTestLog.txt";
string[] allLines = File.ReadAllLines(filePath);
for(int i = 0; i < allLines.Length; i++)
{
if (allLines[i].StartsWith("hello"))
{
allLines[i] += " salmon";
}
}
File.WriteAllLines(filePath, allLines);
Try this:
string path = #"C:\testFolder\newTestLog.txt";
var lines = File.ReadLines(path).Select(l => l + l.StartsWith("hello")?" salmon":"");
foreach (string line in lines)
Console.WriteLine(line);
Note that this still only writes the results to the Console, as your sample does. It's not clear what you really want to happen with the output.
If you want this saved to the original file, you've opened up a small can of worms. Think of all of the data in your file as if it's stored in one contiguous block1. If you append text to any line in the file, that text has nowhere to go but to overwrite the beginning of the next. As a practical matter, if you need to modify file, this often means either writing out a whole new file, and then deleting/renaming when done, or alternatively keeping the whole file in memory and writing it all from start to finish.
Using the 2nd approach, where we keep everything in memory, you can do this:
string path = #"C:\testFolder\newTestLog.txt";
var lines = File.ReadAllLines(path).Select(l => l + l.StartsWith("hello")?" salmon":"");
File.WriteAllLines(path, lines);
1 In fact, a file may be split into several fragments on the disk, but even so, each fragment is presented to your program as part of a single whole.

Replace Linefeeds in Text file

I got a text file where each row ends with CRLF which is fine, but file got some rows with LF within the row content.
Am trying to replace the LF which are within the row content as below:
var fileContent = File.ReadAllText(fileName);
fileContent = Regex.Replace(fileContent, #"(?<!\r)\n", " ");
File.WriteAllText(fileName, fileContent);
This works fine. But when am trying to deal with large file (more than 150mb), throws memory exception.
Tried with
List<string> text = File.ReadAllLines(filePath).ToList();
to read lines and replace by line. But this doesn't work as it splits like on LF
How can I force to split lines by CRLF
You can use the File.ReadLines that returns IEnumerable which means that it only extract one line at a time when needed using the yield functionality.
After successfully writing to anotherFilename we then deleting fileName and moving anotherFilename to his position.
foreach (var line in File.ReadLines(fileName))
{
File.WriteAllText(anotherFilename, line + Environment.NewLine);
}
File.Delete(fileName);
File.Move(anotherFilename, filename);
Note: Haven't been tested.

Remove lines from Text file c#

I have a text file from which I would like to remove an entire line of text. I want to delete the entire line of text if the first amount of characters in that line exceed a certain amount before the white space starts in that line, I hope that makes sense.
Example:
1234567890************** (* = white space such as SPACE or TAB)
1234567890123********** (* = white space such as SPACE or TAB)
The amount of characters before white space in Example line 2 exceed 10 characters so the entire line of text should be deleted.
Thanks in advance.
first read the text in, line by line.
for each line check the first 10th chars. If they are not an "invalid char" (tab or space) include the line in the final string. Then store the final string. (you can overwrite the original file if needed)
List<char> invalidChars = new List<char> {" ", ";"};
string finalString = "";
using (StreamReader sr = new StreamReader("TestFile.txt"))
{
//grab line
String line = sr.ReadToEnd();
//grab first 10 chars of the line
string firstChars = line.substring(0,10);
//check if contains
bool hasInvalidChars = false;
foreach(char c in invalidChars)
{
if(firstChars.toLowerInvariant().IndexOf(c) == 1)
hasInvalidChars = true;
}
if(!hasInvalidChars)
finalString += line + Environment.NewLine;
}
//now store results
using (System.IO.StreamWriter file =
new System.IO.StreamWriter(#"results.txt"))
{
file.write(finalString);
}
then break the line into pieces:
include reference =>using System.IO;
give you file Path where you have place your file and then call stream writer to write that file as i have write "i am good"
using (StreamWriter sw = new StreamWriter(FilePath))
{
sw.Write("i am good");
}

Reading multiple lines of text if it starts with a specific token

:58A:/C/81000098099CL
CBNINGLA
:72:/CODTYPTR/012
/CLEARING/0003
/SGI/DBLNNGLA
am trying to read the swift message above, line :58A: and line :72:, am having a little issue. My code only reads line :58A: like this C/81000098099CL, but I want it to read down the line before getting to line :72:, in short, the output should be like this for line :58A: C/81000098099CL CBNINGLA.
Same also for line :72:, this is because the messages come formatted in this form. This is my code below
if (line.StartsWith(":58A:"))
{
string[] narr = line.Split('/');
inflow202.BENEFICIARY_INSTITUTION = narr[2];
}
if (line.StartsWith(":72:"))
{
inflow202.RECEIVER_INFORMATION = line.Substring(5);
}
You can replace all new lines not followed by : with spaces (or empty string).
string output = Regex.Replace(text, #"\r?\n(?!:)", " ");
string[] lines = output.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string line in lines)
{
if (line.StartsWith(":58A:"))
{
}
else if (line.StartsWith(":72:"))
{
}
}
If the message always comes formatted in this form and : never occurs in the text except for these line starters, consider splitting the whole text into an array by : first. On 0th position there will be nothing, on all odd positions will be the number, on all even positions will be the content until next :. This solution will work providing that you are able to read the whole input into a single string first. I.e. having string message, you can do something like:
var splitted = message.Split(':');
for (i=1;i<= splitted.Length -1; i+=2){
if (splitted[i] == "58A") {
//do what you need to do, the text you need is stored in splitted[i+1]
}
...
}

how to replace a character in a string and save into text file in c#

I'm trying to replace pipe symbol(|) with new line(\n) in my text(test1.txt) file. But when I'm trying to save it in text(test2.text) file the result is not coming in my test2.txt file but I see the result in my console window. Any one please help on this.
string lines = File.ReadAllText(#"C:\NetProject\Nag Assignments\hi.txt");
//string input = "abcd|efghijk|lmnopqrstuvwxyz";
lines = lines.Replace('|', '\n');
File.WriteAllText(#"C:\NetProject\Nag Assignments\hi2.txt", lines);
Console.WriteLine(lines);
You can try this one:
lines = lines.Replace("|", Environment.NewLine);
It returns "\r\n", for non-Unix platforms according to documentation.
Seems like you want multiple things here. (both original question and subsequent comments)
One is to separate the lines and be able to reference them separately:
string[] separatedLines = lines.Split('|');
The other is to join them back together with a different separator:
string rejoinedLines = string.Join(Environment.NewLine, separatedLines);
You then have access to the individual lines from the separatedLines variable above such as separatedLines[0] and you can also write the rejoinedLines variable back to the other file like you wanted.
EDIT: For example, the following code:
string lines = "a|bc|def";
string[] separatedLines = lines.Split('|');
string rejoinedLines = string.Join(Environment.NewLine, separatedLines);
for (int i = 0; i < separatedLines.Length; i++)
{
Console.WriteLine("Line {0}: {1}", i + 1, separatedLines[i]);
}
Gives output of:
Line 1: a
Line 2: bc
Line 3: def
Instead of:
lines = lines.Replace('|', '\n');
Try:
lines = lines.Replace("|","\r\n");
string[] space = lines.Split ('|');
Will save every substring in space.
The line break should be \r\n for carriage return. It depends if you are reading a file binary or text mode. \n is used in text mode while \r\n is used in binary mode.

Categories

Resources