C# 如何读取包含行的特定文本,然后将此文本附加到缺少此文本行的多个文件的文本中?
我有多个扩展名为*.mol的文件。在其中的最后一行中有“M END”文本。我需要一个程序读取所有这些文件,搜索文件中的“M END”行,并将此“M END”写入文件末尾没有“M END”行的文件中。 我编写了以下C#代码,但它不起作用C# 如何读取包含行的特定文本,然后将此文本附加到缺少此文本行的多个文件的文本中?,c#,file-io,C#,File Io,我有多个扩展名为*.mol的文件。在其中的最后一行中有“M END”文本。我需要一个程序读取所有这些文件,搜索文件中的“M END”行,并将此“M END”写入文件末尾没有“M END”行的文件中。 我编写了以下C#代码,但它不起作用 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace ConsoleApplicatio
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication6
{
class Program
{
static void Main(string[] args)
{
foreach (string fileName in Directory.GetFiles("C:\\abc\\", "*.mol"))
{
System.IO.StreamReader file = new System.IO.StreamReader(fileName);
if ((file.ReadLine()) != ("M END"))
{
File.AppendAllText(fileName, "M END" + Environment.NewLine);
}
}
}
}
}
请帮帮我!
谢谢你的回答 如果你的文件不大,你可以试试这个
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication6
{
class Program
{
static void Main(string[] args)
{
foreach (string fileName in Directory.GetFiles("C:\\abc\\", "*.mol"))
{
bool shouldAddMEnd = false;
using (System.IO.StreamReader sw = new System.IO.StreamReader(fileName))
{
shouldAddMEnd = !sw.ReadToEnd().EndsWith("M END");
}
if (shouldAddMEnd)
File.AppendAllText(fileName, "M END" + Environment.NewLine);
}
}
}
}
我试过了,但还是不行。调试过程中出现与我的代码中相同的错误:“进程无法访问文件'C:\abc\2ap-15.mol',因为它正被另一个进程使用。”它在以下行停止:“file.AppendAllText(fileName,“M END”+Environment.NewLine);”