写入一个文本文件
问题描述:
我有这些内容写入一个文本文件
balamurugan,rajendran,chendurpandian
christopher
updateba
,我已阅读这些文件,搜索的关键字ba
和 我试图在另一个文本文件log.txt
写入一个文本文件,但执行后,我代码 我得到第三行仅作为
`LineNo : 2 : updateba`
我需要得到这两个线
LineNo : 0 : balamurugan,rajendran,chendurpandian
LineNo : 2 : updateba
我使用此代码我已经使用这个样本link text
任何建议写入一个文本文件
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
{
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>");
}
???
答
您正在致电WriteAllText
- 此将覆盖该文件;也许你应该File.AppendAllText
?或者,更有效,首先使用StreamWriter
- 即
using (var dest = File.CreateText(path))
{
while (loopCondition)
{
// snip
dest.WriteLine(nextLineToWrite);
}
}
减少代码中的问题的东西像最小的键码,喜欢的东西:
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
创建一个新文件,将内容写入文件,然后关闭该文件。 如果目标文件已经存在,它将被覆盖。
来源。 http://msdn.microsoft.com/en-us/library/system.io.file.writealltext.aspx
您可能想制作一个缓冲区,并在完成后将文件写入缓冲区。
编辑该死的20秒太晚了。
答
你需要AppendAllText
它接缝你搞乱与编码。强制编码为'默认'或'UTF-8',你将不再有这些问题 – balexandre 2010-11-22 12:14:54