line breaks and blank lines ignored - c#

I am trying to read some text from a txt file with following code:
using (StreamReader sr =
File.OpenText(System.IO.Path.GetFullPath("OrderEmailBody.txt")))
{
String input;
while ((input = sr.ReadLine()) != null)
{
emailBody += input;
}
}
The txt file has some blank lines and line breaks but this code is ignoring all line breaks and blank lines in txt file. Please suggest how to fix it?

It doesn't ignore them, you just don't add them to your mail body.
emailBody += input + Environment.NewLine;

using (StreamReader sr =
File.OpenText(System.IO.Path.GetFullPath("OrderEmailBody.txt")))
{
String input;
while ((input = sr.ReadLine()) != null)
{
emailBody += input;
email += Environment.NewLine;
}
}

Related

C# Regular expression To replace all matches in the string

I Have one text file and I want to replaces all matches in each line, so I defined Pattern and I loop through to the text file after I want to write the result in another file, unfortunately my pattern is only replace first occurrence of the word what did |I do in a wrong way?
Content of text file:
"testebook kok o testebook\ntestbbb1232 joj ds testbbb1232"
using System.Text.RegularExpressions;
string filePath = "test.txt";
string fileNewPath = "test1.txt";
string ma = #"^test[0-9a-zA-Z]+";
string newString = string.Empty;
using(StreamReader sr = new(filePath)){
string line = sr.ReadLine();
while (line != null){
while(Regex.IsMatch(line, ma) != false){
line = Regex.Replace(line, ma, "");
}
newString += line + "\n";
line = sr.ReadLine();
}
}
using(StreamWriter sw = new(fileNewPath)){
sw.WriteLine(newString);
}
Your code is correct but your regex pattern is not correct.
you should write this:
string ma = #"test[0-9a-zA-Z]+";
The letter "^" has removed from pattern
So I modified My pattern and remove start with character and everything works now as desired
using System.Text.RegularExpressions;
string filePath = "test.txt";
string fileNewPath = "test1.txt";
MatchesFinder test = new(filePath, fileNewPath);
test.RunTheProcess();
class MatchesFinder{
private string filePath;
private string fileNewPath;
private string ma = #"test[a-zA-Z0-9]+";
public MatchesFinder(string filePath,string fileNewPath){
this.filePath = filePath;
this.fileNewPath = fileNewPath;
}
public void RunTheProcess(){
string newString = string.Empty;
using(StreamReader sr = new(filePath)){
string line = sr.ReadLine();
while (line != null){
while(Regex.IsMatch(line, ma) != false){
line = Regex.Replace(line, ma, string.Empty);
}
newString += line.TrimStart() + "\n";
line = sr.ReadLine();
}
}
using(StreamWriter sw = new(fileNewPath)){
sw.WriteLine(newString);
}
}
}
I think you don´t need to check IsMatch separately, just calling Regex.Replace should yield the same result.
Also, newString += line.TrimStart() + "\n"; means you´re copying all the lines you´ve already checked every time you append a new line. I´d either write directly to the output stream or at least use a StringBuilder if you really want to have the full file in memory for some reason.
Something like this:
using var sw = new StreamWriter(fileNewPath);
using var sr = new StreamReader(filePath);
var line = sr.ReadLine();
while (line != null){
line = Regex.Replace(line, ma, string.Empty);
sw.WriteLine(line.TrimStart());
line = sr.ReadLine();
}

read .csv file into 1D array c#

I would like to convert this code from java to C#
I need to write line by line from csv and store it in an array?
String csvFile = "data.csv";
String line = "";
String cvsSplitBy = ",";
try (BufferedReader br = new BufferedReader(new FileReader(csvFile)))
{
while ((line = br.readLine()) != null)
{
// use comma as separator
String[] data = line.split(cvsSplitBy);
System.out.println(Integer.parseInt(data[0]) + " "+data[1] + " "+data[2] );
}
}
catch (IOException e)
{
e.printStackTrace();
}
Any suggestions?
If you are trying to parse each record/row into array, this might help.
using (StreamReader sr = new StreamReader("maybyourfilepat\data.csv"))
{
string line = sr.ReadLine();
//incase if you want to ignore the header
while (line != null)
{
string[] strCols = line.Split(',');
line = sr.ReadLine();
}
}

Get text using Regex and line number

I need to find strings as follows in a file:
_["Some text"];
or
_.Plural(1, "Some text", "Some text plural);
I am looping file text lines using:
using (StreamReader reader = File.OpenText(file)) {
String line;
while ((line = reader.ReadLine()) != null) {
}
}
In each line I need to get:
"Some text"
OR
"Some text", "Some text plural"
And in both cases I need to get the line number inside the file for each instance.
How can I do with Regex?
Using the pattern and logic from these SO posts:
https://stackoverflow.com/a/171483/1634205
https://stackoverflow.com/a/4892517/1634205
And following this tutorial:
https://www.dotnetperls.com/regex-file
Try this:
static void Main(string[] args)
{
Regex pattern = new Regex("\"(.*?)\"");
string file = #"C:\where\your-file\is\file.txt";
using (StreamReader reader = File.OpenText(file))
{
string line;
while ((line = reader.ReadLine()) != null)
{
foreach (Match match in pattern.Matches(line))
{
Console.WriteLine(match.Value);
}
}
}
Console.ReadLine();
}

find a line and read/display the next line in text document C#

I have this code so far. It looks through a text document and displays lines with the word word in them. I want to make it skip that line and display the next one in the text document, how do I do that?
e.g. it looks thought the text document and finds a line with the word "word" in it and then displays the line that comes after it no other line
string line;
// Read the file and display it line by line.
System.IO.StreamReader file = new System.IO.StreamReader("test.txt");
while ((line = file.ReadLine()) != null)
{
if (line.Contains("word"))
{
Console.WriteLine(line);
}
}
file.Close();
If you're trying to write the line following an occurence of word in a line, try this:
int counter = 0;
bool writeNextLine = false;
string line;
// Read the file and display it line by line.
System.IO.StreamReader file = new System.IO.StreamReader("test.txt");
while ((line = file.ReadLine()) != null)
{
if (writeNextLine)
{
Console.WriteLine(line);
}
writeNextLine = line.Contains("word");
counter++;
}
file.Close();
Something like this will show all the lines except empty lines and lines with the word "word"
using (var rdr = new StreamReader(#"C:\Users\Gebruiker\Desktop\text.txt"))
{
while (!(rdr.EndOfStream))
{
var line = rdr.ReadLine();
if (!(line.Contains("word")) && (line != String.Empty))
{
Console.WriteLine(line);
}
}
}
Console.ReadKey();
This should display all lines after those that contain "word".
int counter = 0;
string line;
System.IO.StreamReader file = new System.IO.StreamReader("test.txt");
while ((line = file.ReadLine()) != null)
{
if (line.Contains("word"))
{
if ((line = file.ReadLine()) != null)
Console.WriteLine(line);
}
counter++;
}
file.Close();

reading html file and display in CKEditor

I am currently using CKEditor for my project to read and display the content of a html file.
However, instead of getting the content of the file, all I get is a string: < html > display in the editor.
But if I write the content directly to the page using response.write, then all the content of the file is displayed correctly.
this is the code snippet I used to read the file:
strPathToConvert = Server.MapPath("~/convert/");
object filetosave = strPathToConvert + "paper.htm";
StreamReader reader = new StreamReader(filetosave.ToString());
string content = "";
while ((content = reader.ReadLine()) != null)
{
if ((content == "") || (content == " "))
{ continue; }
CKEditor1.Text = content;
//Response.Write(content);
}
Can anybody help me to solve this problem?
Many Thanks.
You are in a while loop and you are overwriting the contents of CKEditor every time since you use = instead of +=. Your loops should be:
StreamReader reader = new StreamReader(filetosave.ToString());
string content = "";
while ((content = reader.ReadLine()) != null)
{
if ((content == "") || (content == " "))
{ continue; }
CKEditor1.Text += content;
//Response.Write(content);
}
a better way would probably be to use
string content;
string line;
using (StreamReader reader = new StreamReader(filetosave.ToString())
{
while ((line= reader.ReadLine()) != null)
{
content += line;
}
}
CKEditor1.Text = content;

Categories

Resources