how do i read the second line of text in visual studio 2012 c#
the txt file
user123
**12345**
asdfd
i want to get the second line in one button1_click and show it to textblock2
i did try learn from here
How do I read a specified line in a text file?
and here
How to skip first line and start reading file from second line in C#
but no one of these works because theres difference i couldnt apply in my code
any help?
=================================================================================
sorry to confusing you all
actually im really lacking experience in programming and i hardly know how to use it
right now im using vs2012 in windows8 , is that mean i was coding in winrt?
btw , i appreciate all your help and successfully applying answer to my code
this is the actual code
var file = await ApplicationData.Current.LocalFolder.GetFileAsync(tb1.Text+".txt");
var line = await FileIO.ReadLinesAsync(file);
if (tb2.Text == line[2])
{
tb3.Text = (line[1]);
}
var desiredText = File.ReadLines("C:\myfile.txt").ElementAt(1);
File.ReadLines() returns an String[] of the lines in a file. The index of the second line is 1. See this.
try
var desiredText = File.ReadLines("C:\myfile.txt");
textbox1.text = desiredText[1];
Just call a .ReadLine() before you start capturing the content of the file.
Essentially this will make the reader skip the first line of the file and take only the 2nd line and all lines that follow it.
// Try this to take the second line.
string line;
using (var file_read = new StreamReader(your_file))
{
file_read.ReadLine();
line = file_read.ReadLine();
}
textBox1.Text = line.ToString();
Related
I have a WPF Application which takes an input file path from user and then at the backend open the text file and try to read single character from the file.
fs = File.OpenRead(fileName);
var sr = new StreamReader(fs);
int c;
while ((c = sr.Read()) != -1)
{
Console.Write((char)c); //to check character read from file
try
{
frequencyMap.Add((char)c, 1);
}
catch
{
frequencyMap[(char)c] += 1;
}
}
Here frequencyMap is the dictionary in which character and it's frequency is stored.
This is one method no matter whatever i do the reading from file is always slow even if i try to read the whole text. On output window i see
Area selected is the part of input from the file.
Files upto 2KBs are fine but reading from files like 20KB really gives a hard time.
Now I read that using threads can solve this problem i just don't know how.
My Question is how can i read data from files fastly? if using threads is the solution then how to implement it?
i am new to this so kindly help me.
Thanks
Don't read it by character, read it for example by line, and process each string in a loop. Also Exception is not a way to check if the key exists in the Dictionary.
using (var sr = new StreamReader(fileName))
{
while (!sr.EndOfStream)
{
string s = sr.ReadLine();
Debug.WriteLine(s); //to check string read from file
foreach (char c in s)
{
if (frequencyMap.ContainsKey(c))
frequencyMap[c]++;
else
frequencyMap.Add(c, 1);
}
}
}
Firstly I hope the Console.WrieLine is purely test code. Writing to the console for every character will slow down your processing considerably.
Secondly, it appears from the screen shot you shared that your application is throwing a lot of exceptions. Throwing exceptions is not cheap either in a tight loop.
Thirdly I would recommend you profile your application (visual studio provides a profiler) to help you pin point where exactly your application is spending it’s time.
I am working on a c# project.
I am trying to send a logfile via email whenever application gets crashed.
however logfile is a little bit larger in size.
So I thought that i should include only a specific portion of logfile.
For that I am trying to read all the lines after the last instance of line with specified keyword.(in my case "Application Started")
since Application get restarted many times(due to crashing), 'Application Started' gets printed many times in file. So I would only want last print of line containing 'Application Started' & lines after that until end of file.
I require help to figure out how can i do this.
I have just started with Basic code as of now.
System.IO.StreamReader file = new System.IO.StreamReader("c:\\mylogfile.txt");
while((line = file.ReadLine()) != null)
{
if ( line.Contains("keyword") )
{
}
}
Read the file, line-by-line, until you find your keyword. Once you find your keyword, start pushing every line after that into a List<string>. If you find another line with your keyword, just Clear your list and start refilling it from that point.
Something like:
List<string> buffer = new List<string>();
using (var sin = new StreamReader("pathtomylogfile"))
{
string line;
bool read;
while ((line = sin.ReadLine())!=null)
{
if (line.Contains("keyword"))
{
buffer.Clear();
read = true;
}
if (read)
{
buffer.Add(line);
}
}
// now buffer has the last entry
// you could use string.Join to put it back together in a single string
var lastEntry = string.Join("\n",buffer);
}
If the number of lines in each entry is very large, it might be more efficient to scan the file first to find the last entry and then loop again to extract it. If the whole log file isn't that large, it might be more efficient to just ReadToEnd and then use LastIndexOf to find the start of the last entry.
Read everything from the file and then select the portion you want.
string lines = System.IO.File.ReadAllText("c:\\mylogfile.txt");
int start_index = lines.LastIndexOf("Application Started");
string needed_portion = lines.Substring(start_index);
SendEmail(needed_portion);
I advise you to use a proper logger, like log4net or NLogger.
You can configure it to save to multiple files - one containing complete logs, other containing errors/exceptions only. Also you can set maximum size of log files, etc. Or can configure them to send you a mail if exception occours.
Of course this does not solves your current problem, for it there is some solution above.
But I would try simpler methods, like trying out Notepad++ - it can handle bigger files (last time i've formatted a 30MB XML document with it, it took about 20 mins, but he did it! With simple text files there should be much better perf.). Or if you open the file for reading only (not for editing) you may get much better performance (in Windows).
I am looking to use a text file to make a really basic way of controlling a robot
To do this I would like the have a txt file like below
move #1 P1453 #5 p983 T2000
wait 2000
If I could read each line and use the first word to decide what to do with the data following it. I would need to be able to serial.wrightline the Text following the word move and use the word wait to pause the program in milliseconds. I have found how to read each line of a file but am unaware of how to
separate the word's at the start of the line so i can just use the data following
I don't understand this part:
I have found how to read each line of a file but am unaware of how to
separate the word's at the start of the line
This is how I do this:
StreamReader sr = new StreamReader("file1.txt");
while ( !sr.EndOfStream )
{
string line = sr.ReadLine();
string[] parts = line.Split(' ');
string command = parts[0].Trim();
//Use parts[x] where x > 0 to extract other items of the line
}
I think my question is simple. I've searched but not found a solution for the method that I'm actually using.
I save the content of a listbox into a text file with success, but I'm having problem on load.
For create the file, I use:
using(StreamWriter file = File.CreateText(path))
To write the content from the listbox to file, I use:
foreach (string content in listDOF.Items)
{
file.WriteLine(content);
}
This works very well.
Now, I just need load the saved content with succes.
I've tried:
if (File.Exists(filesrc))
{
File.OpenRead(filesrc);
string[] line = System.IO.File.ReadAllLines(filesrc);
listDOF.Items.Add(line);
}
But this does not work and give me an exception.
How to do this correctily? Thanks all in advance! :)
You are adding an array of strings. The method to use is AddRange
string[] lines = System.IO.File.ReadAllLines(filesrc);
listDOF.Items.AddRange(lines);
The File.OpenRead is not needed. You could remove that line
I am writing a text into a file. I am getting a column from database and stored it in a string and writing it in a text file. That column contains c# code and it is writing like a single line with small squares for next line(space). I need to write it line by line. Here is my code.
using (var dest = File.AppendText(Path.Combine(_logFolderPath, "a.txt")))
{
dest.WriteLine(line.TrimStart());
}
Any suggestion?
Does Notepad show small squares for new lines, but when you look at the file in Visual Studio it's OK? If so, my guess is that this will fix it:
dest.WriteLine(line.TrimStart().Replace("\n", Environment.NewLine));
try this
File.AppendAllText(Path.Combine(_logFolderPath, "a.txt",
line.Trim() + Environment.NewLine));
dest.WriteLine(line.TrimStart().Replace("\n", Environment.NewLine).Replace("\r", Environment.NewLine));