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();
}
Related
I have an application that updates data within a CSV. What I am trying to add is, if the "name" is not in the CSV, then add it. I have tried changing the while to an if/then, but that gave me no results, just a blank line within the CSV.
Code:
using (StreamReader reader = new StreamReader(path))
{
String line;
while ((line = reader.ReadLine()) != null)
{
if (line.Split(',')[0].Equals("newName"))
{
String[] split = line.Split(',');
split[1] = tPoints.ToString();
line = String.Join(",", split);
}
lines.Add(line);
}
}
using (StreamWriter writer = new StreamWriter(path))
{
foreach (String line in lines)
writer.WriteLine(line);
}
Current CSV Data:
name,734937
If item is NOT found, I am trying have it add a new row. So expected result would be something similar to below:
name,734937
newName,0
You can try something like this:
bool termFound = false;
string searchTerm = "newName";
var lines = new List<string>();
using (StreamReader reader = new StreamReader("input.csv"))
{
string line;
while ((line = reader.ReadLine()) != null)
{
lines.Add(line);
if (line.Split(',')[0].Equals(searchTerm))
termFound = true;
}
}
using (StreamWriter writer = new StreamWriter("output.csv"))
{
foreach (string line in lines)
writer.WriteLine(line);
if(termFound == false)
writer.WriteLine($"{searchTerm},0");
}
I have a few trouble with my project.
My string is
11713,Julia's_Candy,Julia's Candy
1713,Julia's_Head,Julia's Head
Now I am using my code like this string line;
using (StreamReader file = new StreamReader(#"db.txt"))
{
while ((line = file.ReadLine()) != null)
{
if (line.Contains(("1713"+",")))
{
label1.Text = line.Split(',')[2];
}
}
}
I want Julia's Head to be print out but it have the same number that including in 11713,Julia's_Candy,Julia's Candy.And its print Julia's Candy
So I want to ask that how can I fix this code for more accurate.
Thank you
If you split first, you can use the first column as an Id column and search for exact match:
string line;
using (StreamReader file = new StreamReader(#"db.txt"))
{
while ((line = file.ReadLine()) != null)
{
var values = line.Split(",");
if (values[0] == "1713")
{
label1.Text = values[2];
}
}
}
I am reading all lines in a text file using C# 7 as follows:
using (StreamReader reader = File.OpenText(file)) {
String line;
while ((line = reader.ReadLine()) != null) {
}
}
For each line I also need to get the line number.
StreamReader does not seem to have a method for getting the line number.
What is the best way to do this?
I'd just create an integer to keep track of the line number myself.
using (StreamReader reader = File.OpenText(file)) {
var lineNumber = 0;
String line;
while ((line = reader.ReadLine()) != null) {
...
lineNumber++;
}
}
Microsoft also uses such a variable to count the lines in one of the examples: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/file-system/how-to-read-a-text-file-one-line-at-a-time
You should use your own local variable for it, like that:
using (StreamReader reader = File.OpenText(file)) {
String line;
int lineNum=0;
while ((line = reader.ReadLine()) != null) {
++lineNum;
}
}
In addition to the other solutions here, I like to use File.ReadAllLines(string) to create a string[] result and then for (int i = 0; i < result.Length; i++)....
you can compute line number by your self:
using (StreamReader reader = File.OpenText(file)) {
String line;
int n = 0;
while ((line = reader.ReadLine()) != null) {
n++;
}
}
I know this is already solved and old but I want to share an alternative. The code just returns the line number where it founds a part of the string given, to have the exact one just replace "Contains" with "Equals".
public int GetLineNumber(string lineToFind) {
int lineNum = 0;
string line;
System.IO.StreamReader file = new System.IO.StreamReader("c:\\test.txt");
while ((line = file.ReadLine()) != null) {
lineNum++;
if (line.Contains(lineToFind)) {
return lineNum;
}
}
file.Close();
return -1;
}
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();
I'm reading a file using C# and class TextReader
TextReader reader = new StreamReader(stream);
string line;
while ((line = reader.ReadLine()) != null)
{
if (someCondition)
{
// I want to change "line" and save it into the file I'm reading from
}
}
In a code there is a question: how do I save a changed line to a file I'm reading from and continue reading?
Fast and dirty solution would be:
TextReader reader = new StreamReader(stream);
string line;
StringBuilder sb = new StringBuilder();
while ((line = reader.ReadLine()) != null)
{
if (someCondition)
{
//Change variable line as you wish.
}
sb.Append(line);
}
using (StreamWriter sw = new StreamWriter("filePath"))
{
sw.Write(sb.ToString());
}
or
TextReader reader = new StreamReader(stream);
string line;
String newLines[];
int index = 0;
while ((line = reader.ReadLine()) != null)
{
if (someCondition)
{
//Change variable line as you wish.
}
newLines[index] = line;
index++;
}
using (StreamWriter sw = new StreamWriter("filePath"))
{
foreach (string l in newLines)
{
sw.WriteLine(l);
}
}
If memory is too important you can try this too:
TextReader reader = new StreamReader(stream);
string line;
while ((line = reader.ReadLine()) != null)
{
if (someCondition)
{
//Change variable line as you wish.
}
using (StreamWriter sw = new StreamWriter("filePath"))
{
sw.WriteLine(line);
}
}
The easiest thing is to write a new file, then when finished, replace the old file with the new file. This way you only do writes in one file.
If you try to read/write in the same file, you will run into problems when the content you want to insert is not the exact same size as the content it is replacing.
There is nothing magic about text files. They are just a stream of bytes representing characters in a text encoding. There are no line concept in the file, just separators in the form of newline characters.
If the file is not too large, you should simply rewrite the whole file:
var lines = File.ReadAllLines(path)
.Where(l => someCondition);
File.WriteAllLines(path, lines);
A very simple solution
void Main()
{
var lines = File.ReadAllLines("D:\\temp\\file.txt");
for(int x = 0; x < lines.Length; x++)
{
// Of course this is an example of the condtion
// you should implement your checks
if(lines[x].Contains("CONDITION"))
{
lines[x] = lines[x].Replace("CONDITION", "CONDITION2");
}
}
File.WriteAllLines("D:\\temp\\file.txt", lines);
}
The drawback is the memory usage caused by the in memory lines, but, if we stay around 50MB, it should be handled effortlessly by modern PC.