【问题标题】:C# Insert text from one txt file to another txt fileC#将文本从一个txt文件插入另一个txt文件
【发布时间】: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);)
  • 您实际上并没有读取第二个文件,只是将文件名插入到第一个文件中。

标签: c# text insert


【解决方案1】:

除了使用StreamReaders/Writers,您还可以使用来自File 辅助类的方法。

const string textFileName = @"C:\Users\Public\test1.txt";
const string textToInsertFileName = @"C:\Users\Public\test2.txt";
const int insertAtLineNumber = 2;

List<string> fileContent = File.ReadAllLines(textFileName).ToList();
fileContent.InsertRange(insertAtLineNumber , File.ReadAllLines(textToInsertFileName));

File.WriteAllLines(textFileName, fileContent);

List&lt;string&gt;ArrayList 方便得多。我还重命名了您的几个变量(最值得注意的是textToInsertFileName,并删除了使您的声明混乱的前缀,如果您将鼠标悬停半秒,任何现代 IDE 都会告诉您数据类型)并使用const 声明您的常量。


您最初的问题与您从未阅读过 strTextToInsert 的事实有关,看起来您认为它已经是要插入实际文件名的文本。

【讨论】:

    【解决方案2】:

    在不过多改变结构或类型的情况下,您可以创建一种读取行的方法

    public ArrayList GetFileLines(string fileName)
    {
        var lines = new ArrayList();
        using (var rdr = new StreamReader(fileName))
        {
            string line;
            while ((line = rdr.ReadLine()) != null)
                lines.Add(line);
        }
        return lines;
    }
    

    在最初的问题中,您没有读取第二个文件,在以下示例中,更容易确定您何时读取文件以及每个文件都已读取:

    string strTextFileName = @"C:\Users\Public\test1.txt";
    int iInsertAtLineNumber = 2;
    string strTextToInsert = @"C:\Users\Public\test2.txt";
    ArrayList lines = new ArrayList();
    
    lines.AddRange(GetFileLines(strTextFileName));
    
    lines.InsertRange(iInsertAtLineNumber, GetFileLines(strTextToInsert));
    
    using (var wrtr = new StreamWriter(strTextFileName))
    {
        foreach (string strNewLine in lines)
            wrtr.WriteLine(strNewLine);
    }
    

    注意:如果你包装阅读器或写在 using 语句中,它将自动关闭

    我还没有对此进行测试,它可以做得更好,但希望这能让你指出正确的方向。此解决方案将完全重写第一个文件

    【讨论】:

      猜你喜欢
      • 2021-02-06
      • 1970-01-01
      • 2020-02-21
      • 2016-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-03
      相关资源
      最近更新 更多