I have a text file i want my program to :
1 - display number of lines and file path .
2 - loop through each line .
var lines = File.ReadLines(@"C:\\test.txt");
Edited (The Answer)
public static string[] local_file; // make a string array to load the file into it
int i = 0; // index of lines
try
{
OpenFileDialog op = new OpenFileDialog // use OpenFileDialog to choose your file
{
Filter = "Combos file (*.txt)|*.txt" ;// select only text files
}
if (op.ShowDialog() == DialogResult.OK)
{
local_file= File.ReadAllLines(op.FileName);// load all the contents of the file into the array
string count = "lines = " + Convert.ToString(local_file.Length); // number of lines
string file_name = op.FileName; // show the file name including the path
}
for (i; i < local_file.Length; i++)// loop through each line
{
// do something here remember to use local_file[i] for the lines
}
}catch (Exception exception)
{
MessageBox.Show(exception.Message);
}
Make it easy by filtering the lines which contains name ali. Later you can user foreach to split each line if lines.count is more than 0.
var lines = File.ReadLines(@"C:\Test.txt").Where(l => l.Contains("ali"));
Should look something like this:
string[] lines = File.ReadAllLines(".....");
foreach (string line in lines)
{
if (line.StartsWith("...."))
{
}
}
You can do it all with LINQ:
var parts = File.ReadLines(@"C:\test.txt") // No need to escape backslash here since you're using a verbatim string
.Select(line => line.Split(':'))
.FirstOrDefault(p => p.Length == 2 && p[0] == "ali");
if (parts != null)
{
textBox1.Text = parts[0];
textBox2.Text = parts[1];
}
public static string[] local_file; // make a string array to load the file into it
int i = 0; // index of lines
try
{
OpenFileDialog op = new OpenFileDialog // use OpenFileDialog to choose your file
{
Filter = "Combos file (*.txt)|*.txt" ;// select only text files
}
if (op.ShowDialog() == DialogResult.OK)
{
local_file= File.ReadAllLines(op.FileName);// load all the contents of the file into the array
string count = "lines = " + Convert.ToString(local_file.Length); // number of lines
string file_name = op.FileName; // show the file name including the path
}
for (i; i < local_file.Length; i++)// loop through each line
{
// do something here remember to use local_file[i] for the lines
}
}catch (Exception exception)
{
MessageBox.Show(exception.Message);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.