我有一个包含这些内容的文本文件
balamurugan,rajendran,chendurpandian
christopher
updateba
Run Code Online (Sandbox Code Playgroud)
我已经阅读了这些文件并搜索了一个关键字ba,我试着在另一个文本文件中写入log.txt但在执行我的代码之后我只得到了第三行
`LineNo : 2 : updateba`
Run Code Online (Sandbox Code Playgroud)
我需要得到这两条线
LineNo : 0 : balamurugan,rajendran,chendurpandian
LineNo : 2 : updateba
Run Code Online (Sandbox Code Playgroud)
我正在使用此代码写入文本文件
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>");
}
Run Code Online (Sandbox Code Playgroud)
我使用了这个示例链接文本
有什么建议吗?
你正在打电话WriteAllText- 这会覆盖文件; 也许你应该File.AppendAllText?或者,更有效率,首先使用a StreamWriter- 即
using (var dest = File.CreateText(path))
{
while (loopCondition)
{
// snip
dest.WriteLine(nextLineToWrite);
}
}
Run Code Online (Sandbox Code Playgroud)
在问题的代码减少了一些类似的最小关键代码,是这样的:
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++;
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1489 次 |
| 最近记录: |