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);
}
Related
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();
}
}
I am trying the following code to split the words in a text file.
The file is written like this:
Apple"Juice"Martini
Lemon"Juice"Party
Banana"Smoothie"Aligns
and the code following:
string resource_data = Properties.Resources.textfile;
string[] result = resource_data.Split('"');
foreach (string lines in result)
{
if(comboBox1.Text == result[0])
{
richTextBox2.Text = result[2];
}
}
Taken & edited from a c++ program I was working on which worked perfectly with the same txt file.
String^ resource_data = "textfile.txt";
try
{
StreamReader^ DataIn = File::OpenText(resource_data);
String^ DataStr;
int count = 0;
array<String^>^ result;
array<Char>^ separ = gcnew array<Char>{'"'};
while((DataStr = DataIn->ReadLine()) != nullptr)
{
count++;
result = DataStr->Split(separ);
if(comboBox1->Text == result[0]) // result[0] = Name
{
What the code does..
Read each line as it own.
Gives first word in each line result[0] as second word on each line is result[1] etc.
When I select a word in the combobox I check if it is the same as in the text file and that line is used in result[x].
But in the C# it gives ALL words own result[x] and lines does not matter.
How can I make the following code in c++ to work in C# but having the text file in the resources.resx?
I think I see what the problem is. You first need to split the string resource_data into separate lines. You could do this by splitting resource_data on the new line character(s):
string[] lines = resource_data.Split(new string[1] { Environment.NewLine }, StringSplitOptions.None);
foreach (var line in lines)
{
string[] parts = line.Split('"');
if (comboBox1.Text == result[0])
{
richTextBox2.Text = result[2];
}
}
You could also do this using a StringReader:
using (StringReader reader = new StringReader(resource_data))
{
while (reader.Peek() >= 0)
{
string[] parts = reader.ReadLine().Split('"');
if (comboBox1.Text == result[0])
{
richTextBox2.Text = result[2];
}
}
}
Additionally if you are only storing the path to the file in the resources, you could open the file and read from it:
using (StreamReader reader = File.OpenText(resource_path)) // path to file
{
while (reader.Peek() >= 0)
{
string[] parts = reader.ReadLine().Split('"');
if (comboBox1.Text == result[0])
{
richTextBox2.Text = result[2];
}
}
}
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.");
}
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;
}
}
This is whats going on. I have a huge text file that is suppose to be 1 line per entry. The issue is sometimes the line is broken with a new line.
I edit this entire file and wherever the file doesn't begin with ("\"A) i need to append the current line to the previous line ( replacing \n with " "). Everything I come up with keeps appending the line to a new line. Any help is appricated...
CODE:
public void step1a()
{
string begins = ("\"A");
string betaFilePath = #"C:\ext.txt";
string[] lines = File.ReadAllLines(betaFilePath);
foreach (string line in lines)
{
if (line.StartsWith(begins))
{
File.AppendAllText(#"C:\xt2.txt",line);
File.AppendAllText(#"C:\xt2.txt", "\n");
}
else
{
string line2 = line.Replace(Environment.NewLine, " ");
File.AppendAllText(#"C:\xt2.txt",line2);
}
}
}
Example:
Orig:
"\"A"Hero|apple|orange|for the fun of this
"\"A"Hero|apple|mango|lots of fun always
"\"A"Her|apple|fruit|no
pain is the way
"\"A"Hero|love|stackoverflowpeople|more fun
Resulting:
"\"A"Hero|apple|orange|for the fun of this
"\"A"Hero|apple|mango|lots of fun always
"\"A"Her|apple|fruit|no pain is the way
"\"A"Hero|love|stackoverflowpeople|more fun
my problem isnt the finding the if (line.StartsWith(begins)) its the else statement, it appends line2 to a new line
it seems like your string is not well formated...
try this "\"\\\"A\"" instead
public void step1a()
{
string begins = ("\"\\\"A\"");
string betaFilePath = #"C:\ext.txt";
string[] lines = File.ReadAllLines(betaFilePath);
foreach (string line in lines)
{
if (line.StartsWith(begins))
{
File.AppendAllText(#"C:\xt2.txt",line);
File.AppendAllText(#"C:\xt2.txt", "\n");
}
else
{
string line2 = line.Replace(Environment.NewLine, " ");
File.AppendAllText(#"C:\xt2.txt",line2);
}
}
}
This does what you want:
CopyFileRemovingStrayNewlines(#"C:\ext.txt", #"C:\xt2.txt", #"""\""A");
With this method:
public static void CopyFileRemovingStrayNewlines(string sourcePath, string destinationPath, string linePrefix)
{
string[] lines = File.ReadAllLines(sourcePath);
bool firstLine = true;
foreach (string line in lines)
{
if (line.StartsWith(linePrefix))
{
if (!firstLine)
File.AppendAllText(destinationPath, Environment.NewLine);
else
firstLine = false;
File.AppendAllText(destinationPath, line);
}
else
{
File.AppendAllText(destinationPath, " ");
File.AppendAllText(destinationPath, line);
}
}
}
It does have the problem of appending to an existing file, though. I suggest using a StreamWriter rather than AppendAllText. Like this:
public static void CopyFileRemovingStrayNewlines(string sourcePath, string destinationPath, string linePrefix)
{
string[] lines = File.ReadAllLines(sourcePath);
bool firstLine = true;
using (StreamWriter writer = new StreamWriter(destinationPath, false))
{
foreach (string line in lines)
{
if (line.StartsWith(linePrefix))
{
if (!firstLine)
writer.WriteLine();
else
firstLine = false;
writer.Write(line);
}
else
{
writer.Write(" ");
writer.Write(line);
}
}
}
}
Your problem is that the \ is a C# escape code.
Your string is parsed as "A, because \" is the escape code for a single ".
You should make the begins string an #-string, which does not use escape codes.
You will then need to escape the " by doubling it up.
For example:
const string begins = #"\""A";
Note that the best way to do this is to use a StreamWriter, like this:
using(StreamWriter writer = File.Create(#"C:\xt2.txt"))
{
foreach (string line in lines)
{
if (line.StartsWith(begins))
writer.WriteLine(); //Close the previous line
writer.Write(line);
}
}
Based on #SLaks's example here is some code that should do the trick:
public static void step1a()
{
string betaFilePath = #"C:\ext.txt";
string[] lines = File.ReadAllLines(betaFilePath);
using (StreamWriter writer = new StreamWriter(File.Create(#"C:\xt2.txt")))
{
string buffer = null;
foreach (string line in lines)
{
if (!line.StartsWith(begins))
{
writer.WriteLine(buffer + line);
buffer = null;
}
else
{
if (buffer != null)
writer.WriteLine(buffer);
buffer = line;
}
}
if(buffer != null)
Console.Out.WriteLine(buffer);
}
}