【发布时间】:2014-10-22 15:32:19
【问题描述】:
我想将文本从一个文本文件插入另一个。
例如,我在 C:\Users\Public\Test1.txt 有一个文本文件
first
second
third
forth
我在 C:\Users\Public\Test2.txt 有第二个文本文件
1
2
3
4
我想将 Test2.txt 插入到 Test1.txt
最终结果应该是:
first
second
1
2
3
4
third
forth
应该在第三行插入。
到目前为止,我有这个:
string strTextFileName = @"C:\Users\Public\test1.txt";
int iInsertAtLineNumber = 2;
string strTextToInsert = @"C:\Users\Public\test2.txt";
ArrayList lines = new ArrayList();
StreamReader rdr = new StreamReader(
strTextFileName);
string line;
while ((line = rdr.ReadLine()) != null)
lines.Add(line);
rdr.Close();
if (lines.Count > iInsertAtLineNumber)
lines.Insert(iInsertAtLineNumber,
strTextToInsert);
else
lines.Add(strTextToInsert);
StreamWriter wrtr = new StreamWriter(
strTextFileName);
foreach (string strNewLine in lines)
wrtr.WriteLine(strNewLine);
wrtr.Close();
但是当我运行它时我得到了这个:
first
second
C:\Users\Public\test2.txt
third
forth
提前致谢!
【问题讨论】:
-
您正在插入(一次)strTextToInsert,而不是其内容(lines.Add(strTextToInsert);)
-
您实际上并没有读取第二个文件,只是将文件名插入到第一个文件中。