Custom print text file in richedTextBox - c#

Helo to all. I have a text file called mytext.txt and inside the text have a format like this:
<name1>Myname
age
address
postal code
<name2>Myname
age
address
postal code
....(more of the same)
the problem i have is that i must print this text in a richTextBox in format like this:
<name1>Myname
-age
-address
-postal code
<name2>Myname
-age
-address
-postal code
....(more of the same)
any idea how i must do this ?

I won't give you the exact code, but I can give you a pseudo-code representation of what a working algorithm would look like:
function printTextFile()
{
for(every line in the text file)
// So start the loop through each line.
if(current line does not start with "<")
{
prefix:= " -".
// So we're not at a title part.
}
print(prefix + current line).
// Print out the line with the indent.
prefix:= "".
// reset the prefix.
end for loop.
}

var writer = new StringBuilder();
foreach (var line in File.ReadAllLines("mytext.txt"))
{
writer.AppendLine(!line.StartsWith("<") ? string.Format(" -{0}", line) : line);
}
richTextBox1.Text = writer.ToString();

Related

C# how to append text in end of row text file?

i have text file like this
IPen ID,Datetime,Status,Data Received
is it possible to add some word in end of row. I want append some word so the final result is :
IPen ID,Datetime,Status,Data Received,Data Reply
i already browsing and searching, the result only show append text in new line, but thats not what i want, i want append text in end of row. any suggestion for me?
It's not overly clear what you're asking, but it sounds like you're saying that any line in a file that has the text "IPen ID,Datetime,Status,Data Received" should be replaced with the text "IPen ID,Datetime,Status,Data Received,Data Reply".
If that's the case then this code works:
File
.WriteAllLines(#"path",
File
.ReadAllLines(#"path")
.Select(x =>
x + (x == "IPen ID,Datetime,Status,Data Received" ? ",Data Reply" : "")));
You can add text at the end of an existing file like this:
using (var stream = new StreamWriter("Your file path here"))
{
stream.Write("Your text here");
}
This method will add the text in a new line only if there is already a end of line character on the end of file. Otherwise, it will add on the same line.
This also adds the text only on the end of the file, if you need to select the line or insert into all lines that match a specific condition it will be a little more complicated, but I can show you if you tell me exactly what you need.
EDIT: Since you need to add the text in the middle of a line, we should read all the lines, change then and save them back on the file:
// Define your file path.
var filePath = "Your file path here";
// Fill an array with the lines from the txt file.
var txtLines = File.ReadAllLines(filePath);
// Change all lines into what you want.
var changedLines = ChangeLines(txtLines);
// Write the file with all the changed lines.
File.WriteAllLines(filePath, changedLines);
And this is how to change the lines:
public static IEnumerable<string> ChangeLines(IEnumerable<string> lines)
{
foreach (var line in lines)
{
yield return line.Replace("A C", "A B C");
}
}
This will replace all the occurrences of "A C" with "A B C". If you want to add something after some text, before, split a line in two or whatever you want, you can change this method to do what you want and all the changes will be saved back into the file. I hope that helps.

Alternative to File.AppendAllText for newline

I am trying to read characters from a file and then append them in another file after removing the comments (which are followed by semicolon).
sample data from parent file:
Name- Harly Brown ;Name is Harley Brown
Age- 20 ;Age is 20 years
Desired result:
Name- Harley Brown
Age- 20
I am trying the following code-
StreamReader infile = new StreamReader(floc + "G" + line + ".NC0");
while (infile.Peek() != -1)
{
letter = Convert.ToChar(infile.Read());
if (letter == ';')
{
infile.ReadLine();
}
else
{
System.IO.File.AppendAllText(path, Convert.ToString(letter));
}
}
But the output i am getting is-
Name- Harley Brown Age-20
Its because AppendAllText is not working for the newline. Is there any alternative?
Sure, why not use File.AppendAllLines. See documentation here.
Appends lines to a file, and then closes the file. If the specified file does not exist, this method creates a file, writes the specified lines to the file, and then closes the file.
It takes in any IEnumerable<string> and adds every line to the specified file. So it always adds the line on a new line.
Small example:
const string originalFile = #"D:\Temp\file.txt";
const string newFile = #"D:\Temp\newFile.txt";
// Retrieve all lines from the file.
string[] linesFromFile = File.ReadAllLines(originalFile);
List<string> linesToAppend = new List<string>();
foreach (string line in linesFromFile)
{
// 1. Split the line at the semicolon.
// 2. Take the first index, because the first part is your required result.
// 3. Trim the trailing and leading spaces.
string appendAbleLine = line.Split(';').FirstOrDefault().Trim();
// Add the line to the list of lines to append.
linesToAppend.Add(appendAbleLine);
}
// Append all lines to the file.
File.AppendAllLines(newFile, linesToAppend);
Output:
Name- Harley Brown
Age- 20
You could even change the foreach-loop into a LINQ-expression, if you prefer LINQ:
List<string> linesToAppend = linesFromFile.Select(line => line.Split(';').FirstOrDefault().Trim()).ToList();
Why use char by char comparison when .NET Framework is full of useful string manipulation functions?
Also, don't use a file write function multiple times when you can use it only one time, it's time and resources consuming!
StreamReader stream = new StreamReader("file1.txt");
string str = "";
while ((string line = infile.ReadLine()) != null) { // Get every line of the file.
line = line.Split(';')[0].Trim(); // Remove comment (right part of ;) and useless white characters.
str += line + "\n"; // Add it to our final file contents.
}
File.WriteAllText("file2.txt", str); // Write it to the new file.
You could do this with LINQ, System.File.ReadLines(string), and System.File.WriteAllLines(string, IEnumerable<string>). You could also use System.File.AppendAllLines(string, IEnumerable<string>) in a find-and-replace fashion if that was, in fact, the functionality you were going for. The difference, as the names suggest, is whether it writes everything out as a new file or if it just appends to an existing one.
System.IO.File.WriteAllLines(newPath, System.IO.File.ReadLines(oldPath).Select(c =>
{
int semicolon = c.IndexOf(';');
if (semicolon > -1)
return c.Remove(semicolon);
else
return c;
}));
In case you aren't super familiar with LINQ syntax, the idea here is to loop through each line in the file, and if it contains a semicolon (that is, IndexOf returns something that is over -1) we cut that off, and otherwise, we just return the string. Then we write all of those to the file. The StreamReader equivalent to this would be:
using (StreamReader reader = new StreamReader(oldPath))
using (StreamWriter writer = new StreamWriter(newPath))
{
string line;
while ((line = reader.ReadLine()) != null)
{
int semicolon = line.IndexOf(';');
if (semicolon > -1)
line = c.Remove(semicolon);
writer.WriteLine(line);
}
}
Although, of course, this would feed an extra empty line at the end and the LINQ version wouldn't (as far as I know, it occurs to me that I'm not one hundred percent sure on that, but if someone reading this does know I would appreciate a comment).
Another important thing to note, just looking at your original file, you might want to add in some Trim calls, since it looks like you can have spaces before your semicolons, and I don't imagine you want those copied through.

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]
}
...
}

Messagebox does not parse special char :

I'm new to C#, and i'm trying to parse a csv file line by line, to search for a string inside each line and do some action.
My problem is that after reading the line, I used Messagebox.Show("Line: " + CurrentLine); just to check if the output is correct, but while the line should show something like C:\Users\test\Desktop\598\Root\test.xls, it just shows up C (the first char).
I used the same code on a console application and the output is fine.
Is there anything wrong with the Messagebox.Show to show the char : ?
Here is my code:
var reader = new StreamReader(File.OpenRead(Filename));
string Search = "test";
string CurrentLine = reader.ReadLine();
MessageBox.Show("Line: " + CurrentLine);
Thanks

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