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.");
}
Related
I'm trying to split a text file based on then number of lines contains around 6M lines and each file should always end (last line) with a certain identifier.
What I tried:
using (System.IO.StreamReader sr = new System.IO.StreamReader(inputfile))
{
int fileNumber = 0;
string line = "";
while (!sr.EndOfStream)
{
int count = 0;
//identifier = sr.ReadLine().Substring(0,2);
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(inputfile + ++fileNumber + ".TXT"))
{
sw.AutoFlush = true;
while (!sr.EndOfStream && ++count < 1233123)
{
line = sr.ReadLine();
sw.WriteLine(line);
}
//having problems starting here not sure how to implement the other condition == "JK"
line = sr.ReadLine();
if (count > 1233123 && line.Substring(0,2) == "JK")
{
sw.WriteLine(line);
}
else
{
while (!sr.EndOfStream && line.Substring(0,2) != "JK")
{
line = sr.ReadLine();
sw.WriteLine(line);
}
}
}
}
}
sample input text is like:
AAadsadasdasdasdfsdfsdfs
Bbasfafasfasdfdsfsdfsdff
CCsafsdfasdadfasdfasfsaf
DDasdsfsdfsafdsadfsafasf
JKdfgdsgdsfgsdfgsfgdfgdf
AAfsdfsadfsdfsaadfadasda
BBadfasdfasdfdsfasfasdas
CCadasdsfasdfasfasfasfds
DDsdfsdafasdfsdfdsfsdfsd
EEsadfsfsasafasdfsdfsdfs
FFasfasfadsdfdsadssfsdfs
JKadsadasdasdadsadasdasa
AAadasdasdasdasdasdasdas
BBasdadadadasdasdasdasdd
CCadasdasdasdasdasdasdad
JKsafsdfsdfasfasdfdasfsa
Basically what I'm trying to achieve is have multiple text files that has at least 1233123 lines or more (i.e if line 1233123 does not have "JK" then continue writing to current file till it is found).
While reading and writing files check if your condition, line number greater than 1233123 and line starting with JK, is true. In this case you can stop writing to the file fragment and continue with the next iteration of your most outer loop, which starts writing to the next file.
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(inputfile + ++fileNumber + ".TXT"))
{
sw.AutoFlush = true;
while (!sr.EndOfStream)
{
line = sr.ReadLine();
sw.WriteLine(line);
if(++count > 1233123 && line.Substring(0,2) == "JK")
{
break;
}
}
}
Im Attempting to read a .txt file that is seperated by commas and two lines, currently i have it setup so that it reads the txt file but having trouble with using the.split method with the taxArray, i need to use the .split so i can calulate the differnt values.
string[] taxArray = new string[2];
int count = 0;
try
{
if(File.Exists(filePath))
{
//read the lines from text file add each line to its own array index.
foreach (string line in File.ReadLines(filePath, Encoding.UTF8))
{
taxArray[count] = line;
txtDisplay.Text += taxArray[count] + "\r\n";
count++;
}
}
else
{
MessageBox.Show("This file cannot be found");
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
This currently outputs exactly as i need.
Here was my solution, I was calling to the array before the foreach loop did its job reading the txt file, thanks for the assistance Toby <3
string[] taxArray = new string[2];
int count = 0;
// string incomeBracket = taxArray[0];
//string[] incomeBracketArray = incomeBracket.Split(',');
try
{
if(File.Exists(filePath))
{
//read the lines from text file add each line to its own array index.
foreach (string line in File.ReadLines(filePath, Encoding.UTF8))
{
taxArray[count] = line;
txtDisplay.Text += taxArray[count] + "\r\n";
count++;
}
string[] incomeBracket = taxArray[1].Split(',');
txtDisplay.Text = incomeBracket[0];
else
{
MessageBox.Show("This file cannot be found");
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
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();
}
}
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();
}
}
I need help in searching the text file. I have manage to store the input values to Textfile with ":" separator.
And my result text box is like
friend1:126457890
friend2:123487012
Friend3:798461598
and now I want to search the text file and display result in labels/textbox(read only)
Here is my code to search
private void btn_search_search_Click(object sender, EventArgs e)
{
try
{
if (string.IsNullOrEmpty(txt_search.Text))
{
lbl_search_error.Text = "Please Enter name to search";
}
else
{
StreamReader sr = new StreamReader(#"path.txt");
string line;
string searchkey = txt_search.Text;
sr.ReadToEnd();
while ((line = sr.ReadLine()) != null)
{
if (line.Contains(searchkey))
break;
}
sr.Close();
string[] data = line.Split(':');
txt_result_name.Text = data[0];
txt_result_phno.Text = data[1];
}
}
catch (Exception ex)
{
lbl_search_error.Text = ex.Message;
}
}
but I get
Object reference not set to an instance of an object
I tried to keep break point and chk, error is in this line
string[] data = line.Split(':');
Please help resolving
Thank you for your time
Delete the line sr.ReadToEnd();
Let me give you a different approach using regular expression:
private void btn_search_search_Click(object sender, EventArgs e)
{
StreamReader sr = new StreamReader("Some file");
string line = sr.ReadLine();
string name="";
string number="";
while (line != null)
{
var m = Regex.Match(line, #"([\w]+):([\d]+)<br>");
if (m.Success)
{
name = m.Groups[1].Value;
number = m.Groups[2].Value; // use this name and number variables as per your need
line = sr.ReadLine();
}
else
{
line = sr.ReadLine();
}
}
}
This is a way to go about the problem. Ask any questions if you have
You are getting this error because the value of line is null in: string[] data = line.Split(':');
Take a string variable called temp and assign the value of line to temp in the while loop. Later use this variable instead of line.
Do like this:
private void btn_search_search_Click(object sender, EventArgs e)
{
try
{
if (string.IsNullOrEmpty(txt_search.Text))
{
lbl_search_error.Text = "Please Enter name to search";
}
else
{
StreamReader sr = new StreamReader(#"path.txt");
string line;
string searchkey = txt_search.Text;
sr.ReadToEnd();
string temp;
while ((line = sr.ReadLine()) != null)
{
if (line.Contains(searchkey))
{
temp = line;
break;
}
}
sr.Close();
string[] data = temp.Split(':');
txt_result_name.Text = data[0];
txt_result_phno.Text = data[1];
}
}
catch (Exception ex)
{
lbl_search_error.Text = ex.Message;
}
}