writing to a text file
I have a text file with these contents
balamurugan,rajendran,chendurpandian
christopher
updateba
and i have read these files and searched for a keyword ba
and
i tried to write in another text file log.txt
but after executing my code
i am getting the third line only as
`LineNo : 2 : updateba`
I need to get both these lines
LineNo : 0 : balamurugan,rajendran,chendurpandian
LineNo : 2 : updateba
I am using this code to write to a text file
if (File.Exists(FilePath))
{
// Read the file and display it line by line.
System.IO.StreamReader file = new System.IO.StreamReader(FilePath);
while ((line = file.ReadLine()) != null)
{
if (line.Contains(regMatch))
{
DirectoryInfo Folder = new DirectoryInfo(textboxPath.Text);
if (Folder.Exists)
{
var dir = @"D:\New folder\log";
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
File.WriteAllText(Path.Combine(dir, "log.txt"), "LineNo : " + counter.ToString() + " : " + line + "<br />");
}
else
{
开发者_JS百科 Response.Write("<script language='javascript'>window.alert('Folder not found');</script>");
}
Response.Write("<script language='javascript'>window.alert('Pattern found');</script>");
Response.Write("LineNo : " + counter.ToString()+ " : " + line + "<br />");
}
else
{
Response.Write("<script language='javascript'>window.alert('Pattern not found');</script>");
}
counter++;
}
file.Close();
}
else
{
Response.Write("<script language='javascript'>window.alert('File not found');</script>");
}
i have used this samplelink text
Any suggestion???
You are calling WriteAllText
- this overwrites the file; perhaps you should File.AppendAllText
? Or, more efficiently, use a StreamWriter
in the first place - i.e.
using (var dest = File.CreateText(path))
{
while (loopCondition)
{
// snip
dest.WriteLine(nextLineToWrite);
}
}
Reducing the code in the question to something like the minimal key code, something like:
DirectoryInfo Folder = new DirectoryInfo(textboxPath.Text);
var dir = @"D:\New folder\log";
if (Folder.Exists)
{
if (!Directory.Exists(dir)) Directory.CreateDirectory(dir);
}
if (File.Exists(FilePath))
{
// Read the file and display it line by line.
using (var file = File.OpenText(FilePath))
using (var dest = File.AppendText(Path.Combine(dir, "log.txt")))
{
while ((line = file.ReadLine()) != null)
{
if (line.Contains(regMatch))
{
dest.WriteLine("LineNo : " + counter.ToString() + " : " +
line + "<br />");
}
counter++;
}
}
}
File.WriteAllText
Creates a new file, write the contents to the file, and then closes the file. If the target file already exists, it is overwritten.
Source. http://msdn.microsoft.com/en-us/library/system.io.file.writealltext.aspx
You probably want to make a buffer and write the buffer the file after you are done.
edit damn it 20 seconds too late.
you need AppendAllText
精彩评论