How to read the next line in a text document? - c#

I want to know how to read the next line of a text document.
If I click the button, it should open the text document and read the first line.
Then, if I click the "next" button it should read the next line.
How can I do this second button? In C and other languages there are some commands for this..

You need a StreamReader object and then you can invoke the ReadLine method. Don't forget to add the "#" symbol before file path name.
StreamReader sr = new StreamReader(#"C:\\YourPath.txt");
Then on your button clicks you can do:
var nextLine = sr.ReadLine();
The result of each line will be stored in the nextLine variable.

You can use StreamReader.ReadLine
if (myStreamReader.Peek() >= 0)
{
string line = myStreamReader.ReadLine();
}
If you don't want to keep the file open, you can start by reading all lines into memory using File.ReadAllLines
string[] allLines = File.ReadAllLines(path);

Related

How can I read the first line from every text file in a specific directory and add each line to a listbox in a C# WPF app?

I have a directory that Contains x amount of text files. The first Line on each text file needs to be added to a list box in a WPF application when the application starts. How can I read the first line from every text file and add each line to my list box?
Something like this should do:
foreach (var filePath in Directory.EnumerateFiles(#"c:\folder"))
{
using (var reader = new StreamReader(filePath))
{
var line = reader.ReadLine();
listBox.Items.Add(line);
}
}

reading and querying a txt/log file using c#

i have created a log file example.txt that records events as
Button1 Click event happen ID=xyz DT:3/1/2015 9:27:32 AM
Button2 Click event happen ID=xyz DT:3/1/2015 9:28:32 AM
Button1 Click event happen ID=xyz DT:3/1/2015 9:29:32 AM
Button2 Click event happen ID=xyz DT:3/1/2015 9:30:32 AM
i can read those file but i will get everything written in the log file.\
i have used the following code
try
{
using(FileStream fileStream = new FileStream("c://temp1/example_logfile.txt",FileMode.Open,FileAccess.Read,FileShare.ReadWrite))
{
using(StreamReader streamReader = new StreamReader(fileStream))
{
this.txt.Text = streamReader.ReadToEnd();
}
}
}
I want to read just the Button1 click event. how do you do that?
Use File.ReadLines and a bit of LINQ to get only the lines you're interested in:
var results = File.ReadLines(filePath).Where(x => x.StartsWith("Button1 Click"));
Now you've got a collection of strings representing the matching lines. If you want to display them in a single TextBox, you can flatten the list back out to a single string:
this.txt.Text = String.Join(", ", results);
Or modify the LINQ statement to get, say, the first match only: (assuming at least one match)
this.txt.Text = File.ReadLines(filePath).First(x => x.StartsWith("Button1 Click"));
What about a solution with StreamReader.ReadLine() combined with String.Contains()
String line;
while (!streamReader.EndOfStream) // <= Check for end of file
{
line = streamReader.ReadLine(); // <=Get a single line
if (line.Contains("Button1")) // <= Check for condition ; line contains 'Button1'
{
this.txt.Text += line + "\n"; // <== Append text with a newline
}
}

Process each line separately in selected text

I'm trying to select a set of lines and process each line separately in a text document using c# language. How can i get separate lines to process?
I tried these codes and got struck. Can anyone please help me with this?
EnvDTE.DTE dte = MyPackage.MyPackagePackage.GetGlobalService(typeof(EnvDTE.DTE)) as EnvDTE.DTE;
EnvDTE.TextSelection text = (dte.ActiveDocument.Selection as EnvDTE.TextSelection);
TextSelection interface has got Text property which you can use as string in C#. Further you can split the string to retrieve the lines.
Alternatively TextSelection interface has additional property called TextRanges which has numeric indexers to access each line.
Have a look at this Link form MSDN.
You can use Startpoint and EndPoint for your job.
Also this Link link might be useful to Loop through all the lines from your selection.
If you are reading from a text file this code will help you:
string fileToRead = "D:\\temp.txt"; // Temp.txt is the file to read
if (File.Exists(fileToRead))
{
StreamReader reader = new StreamReader(fileToRead);
do
{
textBox1.Text += reader.ReadLine() + "\r\n"; // Read each line and pass it to the TextBox1
} while (reader.Peek() != -1);
reader.Close(); // Close the file
}

Append a text file starting from a certain location in the source text file

I want to append a text file (let's say "append.txt") in another text file (let's say "original.txt") but not at last line/character of "original.txt". It should append starting from a certain location of a string (let's say "match") found in "original.txt". And ignore all other text in "original.txt" after "match" string's location and start appending the "append.txt" file from the "match" string's location in the "original.txt" file.
The problems that I face are:
I can not load whole files in memory because the files can go up to 100 MB. So, I have decided to use StreamReader and StreamWriter and use ReadLine and WriteLine for line by line append and to get the location of target string in a line to find out from where to start the append process. Is this the best approach?
I would prefer not to use a third temporary file (let's say "temporary.txt") to have final text and then replace "original.txt" with "temporary.txt" because of the large file size transfer. Is it possible to not use a third temporary file?
My current code is:
StreamReader TextFile = new StreamReader("original.txt");
StreamReader TextFileAppend = new StreamReader("append.txt");
StreamWriter TextFileTemp = new StreamWriter("temporary.txt");
sLine = TextFile.ReadLine();
while (!string.IsNullOrEmpty(sLine) && !TextFile.EndOfStream && !sLine.Contains("match"))
{
TextFileTemp.WriteLine(sLine);
sLine = TextFile.ReadLine();
TextFileTemp.WriteLine(sLine);
}
TextFile.Close();
sLine = TextFileAppend.ReadLine();
while (!string.IsNullOrEmpty(sLine) && !TextFileAppend.EndOfStream)
{
sLine = TextFileAppend.ReadLine();
TextFileTemp.WriteLine(sLine);
}
TextFileTemp.Close();
TextFileAppend.Close();
File.Copy("temporary.txt", "original.txt", true);
The above code works fine but requires a temporary third file to save the merged content and then replaces "original.txt" with the merged text file.
There is nothing wrong in the code but I was wondering if a file can be appended from a certain location and not from the end?
First of all, 100 Mb is not out of the range of reading in the entire file contents into a string and then using the in memory functions to go faster. What's important is that manipulating large strings like that may be slow.
Try this:
string originalContents = File.ReadAllText("original.txt");
string insertContents = File.ReadAllText("append.txt");
int index = originalContents .IndexOf("match");
if (index == -1) return;
FileStream stream = new FileStream("original.txt", FileMode.Open);
stream.Position = index;
byte[] insertBytes = Encoding.ASCII.GetBytes(insertContents);
stream.Write(insertBytes);
byte[] endBytes = Encoding.ASCII.GetBytes(originalContents.Substring(index));
stream.Write(endBytes);

StreamWriter Writes everything on same line

I have a small HttpWebRequest that grabs some text from a online .txt file
After it gets it i want to save it to a .txt file on the computer.
Content of the text is formatet like this:
Line one
Line two
Line four
Line Five
Line ten etc.
But when it saves it ends up like this:
Line oneLine twoLine fourLine FiveLine ten etc.
How may I fix this?
Code is as follows:
HttpWebRequest WebReq3 = (HttpWebRequest)WebRequest.Create("http://test.net/test.txt");
HttpWebResponse WebResp3 = (HttpWebResponse)WebReq3.GetResponse();
System.IO.StreamReader sr3 = new System.IO.StreamReader(WebResp3.GetResponseStream());
System.IO.StreamWriter _WriteResult = new StreamWriter(Application.StartupPath + "\Test.txt");
_WriteResult.Write(sr3.ReadToEnd());
_WriteResult.Close();
sr3.Close();
Read data using ReadLine() and write using WriteLine() instead of ReadToEnd() and WriteToEnd().
Remove this line:
_WriteResult.Write(sr3.ReadToEnd());
And modify your code with this:
string readval = sr3.ReadLine();
while(readval != null)
{
_WriteResult.WriteLine(readval);
readval = sr3.ReadLine();
}
For more details, see the documentation.

Categories

Resources