c# function inside while won't cycle - c#

hi everybody i have this code
StreamReader reader = new StreamReader("C:\\Users\\lorenzov\\Desktop\\gi_pulito_neg.txt");
string line = reader.ReadLine();
string app = "";
int i = 0;
while (line != null)
{
i++;
line = reader.ReadLine();
if (line != null)
{
int lunghezza = line.Length;
}
Console.WriteLine(i);
System.Threading.Thread.Sleep(800);
string ris= traduttore.traduci(targetLanguage, line);
// Console.WriteLine(line);
// Console.WriteLine(ris);
// Console.Read();
// app = app + ris;
// System.Threading.Thread.Sleep(50);
File.AppendAllText(#"C:\Users\lorenzov\Desktop\gi_tradotto_neg.txt", ris + Environment.NewLine);
}
the fact is that i have a txt file which i want to translate with this function traduci(targetLanguage,line), the function is ok, i want to translate each line into another file, while is looping the function is blocking at the first loop, if i insert consonle.read() when i press enter the function works...ho can i do? thank you all!

Your code is pretty messy. I would suggest the following method to loop over the StreamReader lines:
using (StreamReader reader = new StreamReader("C:\\Users\\lorenzov\\Desktop\\gi_pulito_neg.txt"))
{
string line;
while (!reader.EndOfStream)
{
line = reader.ReadLine();
// ... process the line
}
}

If ReadLine returns a null, your code will break. better structure:
StreamReader reader = new StreamReader("C:\\Users\\lorenzov\\Desktop\\gi_pulito_neg.txt");
string line;
string app = "";
int i = 0;
while ((line = reader.ReadLine()) != null)
{
i++;
int lunghezza = line.Length;
Console.WriteLine(i);
System.Threading.Thread.Sleep(800);
string ris= traduttore.traduci(targetLanguage, line);
// Console.WriteLine(line);
// Console.WriteLine(ris);
// Console.Read();
// app = app + ris;
// System.Threading.Thread.Sleep(50);
File.AppendAllText(#"C:\Users\lorenzov\Desktop\gi_tradotto_neg.txt", ris + Environment.NewLine);
}

The code as it stands will skip over the first line, as you use ReadLine() twice prior to fist use.
You can restructure the code as
using (StreamReader reader = new StreamReader(#"C:\Users\lorenzov\Desktop\gi_pulito_neg.txt"))
using (StreamWriter writer = new StreamWriter(#"C:\Users\lorenzov\Desktop\gi_tradotto_neg.txt"))
{
string line = reader.ReadLine();
while(line != null)
{
System.Threading.Thread.Sleep(800);
string ris = traduttore.traduci(targetLanguage, line);
writer.WriteLine(ris);
line = reader.ReadLine();
}
}

Related

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 line number when reading a file

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;
}

Writing to temp array from text file

I asked this before but most people don't understand my question.
I have two text files. Gamenam.txt which is the text file I'm reading from, and gamenam_2.txt.
In the gamenam.txt I have strings like this:
01456
02456
05215
05111
01421
03117
05771
01542
04331
05231
I have written a code to count number of times substring "05" appears in text file before substring "01".
My output which is written to gamenam_1.txt is:
01456
02456
05215
05111
2
01421
03117
05771
1
01542
04331
05231
1
This was the code I wrote to achieve
string line;
int counter = 0;
Boolean isFirstLine = true;
try
{
StreamReader sr = new StreamReader("C:\\Files\\gamenam.txt");
StreamWriter sw = new StreamWriter("C:\\Files\\gamenam_1.txt");
while ((line = sr.ReadLine()) != null)
{
if (line.Substring(0, 2) == "01")
{
if (!isFirstLine)
{
sw.WriteLine(counter.ToString());
counter = 0;
}
}
if (line.Substring(0, 2) == "05")
{
counter++;
}
sw.WriteLine(line);
if (sr.Peek() < 0)
{
sw.Write(counter.ToString());
}
isFirstLine = false;
}
sr.Close();
sw.Close();
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.Message);
}
finally
{
Console.WriteLine("Exception finally block.");
}
That code is working perfectly.
Now I have to write a code to print the count of substring "05" before writing lines.
My output should look something like this:
2
01456
02456
05215
05111
1
01421
03117
05771
1
01542
04331
05231
Apparently I should write the lines first to temporary string array, the count and then write count and then after write lines from my temporary array.
I'm new to development so I'm stuck trying to figure out how I'd achieve this.
Any help will highly be appreciated.
Try this
string line;
int counter = 0;
Boolean isFirstLine = true;
try
{
StreamReader sr = new StreamReader("C:\\Files\\gamenam.txt");
StreamWriter sw = new StreamWriter("C:\\Files\\gamenam_1.txt");
var lines = new List<string>(); //Here goes the temp lines
while ((line = sr.ReadLine()) != null)
{
if (line.Substring(0, 2) == "01")
{
if (!isFirstLine)
{
sw.WriteLine(counter.ToString()); //write the number before the lines
foreach(var l in lines)
sw.WriteLine(l); //actually write the lines
counter = 0;
lines.Clear(); //clear the list for next round
}
}
if (line.Substring(0, 2) == "05")
{
counter++;
}
lines.add(line); //instead of writing, just adds the line to the temp list
if (sr.Peek() < 0)
{
sw.WriteLine(counter.ToString()); //writes everything left
foreach(var l in lines)
sw.WriteLine(l);
}
isFirstLine = false;
}
sr.Close();
sw.Close();
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.Message);
}
finally
{
Console.WriteLine("Exception finally block.");
}

Reading and changing a file

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.

Using StreamReader to check if a file contains a string

I have a string that is args[0].
Here is my code so far:
static void Main(string[] args)
{
string latestversion = args[0];
// create reader & open file
using (StreamReader sr = new StreamReader("C:\\Work\\list.txt"))
{
while (sr.Peek() >= 0)
{
// code here
}
}
}
I would like to check if my list.txt file contains args[0]. If it does, then I will create another process StreamWriter to write a string 1 or 0 into the file. How do I do this?
Are you expecting the file to be particularly big? If not, the simplest way of doing it would be to just read the whole thing:
using (StreamReader sr = new StreamReader("C:\\Work\\list.txt"))
{
string contents = sr.ReadToEnd();
if (contents.Contains(args[0]))
{
// ...
}
}
Or:
string contents = File.ReadAllText("C:\\Work\\list.txt");
if (contents.Contains(args[0]))
{
// ...
}
Alternatively, you could read it line by line:
foreach (string line in File.ReadLines("C:\\Work\\list.txt"))
{
if (line.Contains(args[0]))
{
// ...
// Break if you don't need to do anything else
}
}
Or even more LINQ-like:
if (File.ReadLines("C:\\Work\\list.txt").Any(line => line.Contains(args[0])))
{
...
}
Note that ReadLines is only available from .NET 4, but you could reasonably easily call TextReader.ReadLine in a loop yourself instead.
You should not add the ';' at the end of the using statement.
Code to work:
string latestversion = args[0];
using (StreamReader sr = new StreamReader("C:\\Work\\list.txt"))
using (StreamWriter sw = new StreamWriter("C:\\Work\\otherFile.txt"))
{
// loop by lines - for big files
string line = sr.ReadLine();
bool flag = false;
while (line != null)
{
if (line.IndexOf(latestversion) > -1)
{
flag = true;
break;
}
line = sr.ReadLine();
}
if (flag)
sw.Write("1");
else
sw.Write("0");
// other solution - for small files
var fileContents = sr.ReadToEnd();
{
if (fileContents.IndexOf(latestversion) > -1)
sw.Write("1");
else
sw.Write("0");
}
}
if ( System.IO.File.ReadAllText("C:\\Work\\list.txt").Contains( args[0] ) )
{
...
}
The accepted answer reads all file in memory which can be consuming.
Here's an alternative inspired by VMAtm answer
using (var sr = new StreamReader("c:\\path\\to\\file", true))
for (string line; (line = sr.ReadLine()) != null;) //read line by line
if (line.Contains("mystring"))
return true;

Categories

Resources