C# 如何在一行中读取一个特定单词的文本文件,并将整行内容写入另一个文本文件?

C# 如何在一行中读取一个特定单词的文本文件,并将整行内容写入另一个文本文件?,c#,c#-4.0,C#,C# 4.0,我有一个文本文件,名为text1.txt,包含以下行: 4410 Rel testRel1 4411 Dbg testDbg1 4412 Dbg testDbg2 4412 Rel testRel2 4413 Rel testRel3 4413 Dbg testDbg3 4414 Rel testRel4 4415 Rel testRel5 现在,我想把所有带有单词Rel的行写入一个文本文件,比如text2.txt。因此,我的text2.txt应该如下所示: 4410 Rel testRel1

我有一个文本文件,名为text1.txt,包含以下行:

4410 Rel testRel1
4411 Dbg testDbg1
4412 Dbg testDbg2
4412 Rel testRel2
4413 Rel testRel3
4413 Dbg testDbg3
4414 Rel testRel4
4415 Rel testRel5
现在,我想把所有带有单词Rel的行写入一个文本文件,比如text2.txt。因此,我的text2.txt应该如下所示:

4410 Rel testRel1
4412 Rel testRel2
4413 Rel testRel3
4414 Rel testRel4
4415 Rel testRel5
最后,我的代码应该读取text2.txt并返回text2.txti.e最后一行的前四个字符。4415将text1.txt的路径作为输入。 下面是我的代码。可能是我写了一半,但不知道c

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Activities;
using Microsoft.Build.Utilities;
using Microsoft.Build.Framework;
using System.IO;
using Microsoft.TeamFoundation.Build.Client;

namespace Build_Tasks.Activities
{
    [BuildActivity(HostEnvironmentOption.All)]
    public sealed class GetBuildNumber : CodeActivity
    {
        // Define an activity input argument of type string
        public InArgument<string> TextFileName { get; set; }
        public OutArgument<string> setBuildNumber { get; set; }
        private string temp_FilePath = "c:\\temp.txt";

        // If your activity returns a value, derive from CodeActivity<TResult>
        // and return the value from the Execute method.
        protected override void Execute(CodeActivityContext context)
        {
            // Obtain the runtime value of the Text input argument
            string TextFileName = context.GetValue(this.TextFileName);
            string TextFilePath = TextFileName;
            string[] Lines = File.ReadAllLines(TextFilePath);
            //string wordrel = "Rel";
            System.IO.StreamReader file = new System.IO.StreamReader(TextFilePath);
            List<string> Spec = new List<string>();
            string line;
            System.IO.StreamWriter file2 = new System.IO.StreamWriter(temp_FilePath);
            while ((line = file.ReadLine()) != null)
            {
                if(line.Contains("Rel"))
                     {
                        file2.WriteLine(line);
                      }
            }
            var lastline = File.ReadLines(temp_FilePath).Last();
            string number = lastline.Substring(0, 4);
            context.SetValue<string>(this.setBuildNumber, number);
            }
    }
    }

这将遍历原始文件的行,并将相关行复制到新文件:

string tempFile = "text2.txt";
List<string> linesWithREL = new List<string>();
using (var sr = new StreamReader("file.txt"))
using (var sw = new StreamWriter(tempFile))
{
    string line;

    while ((line = sr.ReadLine()) != null)
    {
        //check if the current line should be copied
        if (line.Contains("whatever"))
        {
               linesWithREL.Add(line.Substring(0,4));
               sw.WriteLine(line);
        }
    }
}

这将遍历原始文件的行,并将相关行复制到新文件:

string tempFile = "text2.txt";
List<string> linesWithREL = new List<string>();
using (var sr = new StreamReader("file.txt"))
using (var sw = new StreamWriter(tempFile))
{
    string line;

    while ((line = sr.ReadLine()) != null)
    {
        //check if the current line should be copied
        if (line.Contains("whatever"))
        {
               linesWithREL.Add(line.Substring(0,4));
               sw.WriteLine(line);
        }
    }
}
试试这个:

string path1 = @"C:\data1.txt";
string path2 = @"C:\data2.txt";
string searchKey = "Rel";
List<string> newlines = new List<string>();
foreach (var line in File.ReadLines(path1))
{
if (line.Split(new char[]{' '},
         StringSplitOptions.RemoveEmptyEntries)[1].Contains(searchKey))
{
newlines.Add(line);
}
}
File.WriteAllLines(path2,newlines.ToArray());
试试这个:

string path1 = @"C:\data1.txt";
string path2 = @"C:\data2.txt";
string searchKey = "Rel";
List<string> newlines = new List<string>();
foreach (var line in File.ReadLines(path1))
{
if (line.Split(new char[]{' '},
         StringSplitOptions.RemoveEmptyEntries)[1].Contains(searchKey))
{
newlines.Add(line);
}
}
File.WriteAllLines(path2,newlines.ToArray());
如果file2只需要获取内部版本号,则根本不需要创建它:

protected override void Execute(CodeActivityContext context)
{
    // Obtain the runtime value of the Text input argument
    string TextFileName = context.GetValue(this.TextFileName);
    string TextFilePath = TextFileName;

    string number = null;
    var splitChars = new[]{ ' ' };

    foreach (var line in File.ReadLines(TextFilePath))
    {
        var values = line.Split(splitChars, StringSplitOptions.RemoveEmptyEntries).ToArray();
        if (values.Length < 3)
            continue;

        buildNumber = (values[1] == "Rel" ? values[0] : buildNumber);
    }

    context.SetValue<string>(this.setBuildNumber, number);        
}
而且,由于您只对最后一个版本号感兴趣,因此可以通过不从开始读取文件,而是查找到结尾的流并向后跳,直到找到带有Rel的行来进一步优化此功能。

如果您只需要file2来获取版本号,则根本不需要创建它:

protected override void Execute(CodeActivityContext context)
{
    // Obtain the runtime value of the Text input argument
    string TextFileName = context.GetValue(this.TextFileName);
    string TextFilePath = TextFileName;

    string number = null;
    var splitChars = new[]{ ' ' };

    foreach (var line in File.ReadLines(TextFilePath))
    {
        var values = line.Split(splitChars, StringSplitOptions.RemoveEmptyEntries).ToArray();
        if (values.Length < 3)
            continue;

        buildNumber = (values[1] == "Rel" ? values[0] : buildNumber);
    }

    context.SetValue<string>(this.setBuildNumber, number);        
}

而且,由于您只对上一个版本号感兴趣,因此可以通过不从开始读取文件,而是查找流到结尾,然后向后跳,直到找到带有Rel的行来进一步优化此功能。

好的,正如我读到的一些注释所示,您的问题不在于读/写,而在于这一行:

var lastline = File.ReadLines(temp_FilePath).Last();
在对同一文件使用File.ReadLine之前,必须先关闭编写器

file2.Flush();
file2.Close();
var lastline = File.ReadLines(temp_FilePath).Last();

如果您想优化代码,添加了一些答案,无需重复。

好的,当我阅读一些评论时,您的问题不在读/写,而是在这一行:

var lastline = File.ReadLines(temp_FilePath).Last();
在对同一文件使用File.ReadLine之前,必须先关闭编写器

file2.Flush();
file2.Close();
var lastline = File.ReadLines(temp_FilePath).Last();
如果您想优化代码,添加了一些答案,无需重复。

试试这个

    static void Main(string[] args)
    {
        int counter = 0;
        string line;

        // Read the file(your SXA file) and display it line by line.
        System.IO.StreamReader file = new System.IO.StreamReader("c:\\SXA63.txt");
        while((line = file.ReadLine()) != null)
         {         //File to write lines which contain Rel. 
                   using(StreamWriter writer = new StreamWriter("c:\\Relfile.txt",true))
                    {
                       if(line.Contains("Rel"))
                      writer.WriteLine(line);
                    }
            counter++;

        }
        String last = File.ReadLines(@"C:\Relfile.txt").Last();
        string buildNo = last.Substring(0, 4);
        file.Close();
        Console.ReadKey();

    }
}
试试这个

    static void Main(string[] args)
    {
        int counter = 0;
        string line;

        // Read the file(your SXA file) and display it line by line.
        System.IO.StreamReader file = new System.IO.StreamReader("c:\\SXA63.txt");
        while((line = file.ReadLine()) != null)
         {         //File to write lines which contain Rel. 
                   using(StreamWriter writer = new StreamWriter("c:\\Relfile.txt",true))
                    {
                       if(line.Contains("Rel"))
                      writer.WriteLine(line);
                    }
            counter++;

        }
        String last = File.ReadLines(@"C:\Relfile.txt").Last();
        string buildNo = last.Substring(0, 4);
        file.Close();
        Console.ReadKey();

    }
}

如果还有其他方法,比如读取数组中的行而不是text2.txt,即使这样也会有所帮助。我的text2.txt是一个临时文件,用于实现上述指定。您不必创建file2.txt,也不必将行存储在数组中,只需获取我在回答中指出的版本号。如果有任何其他方法,例如将行读取到数组而不是text2.txt,即使这样也会有所帮助。我的text2.txt是一个临时文件,用于实现上述指定。您不必创建file2.txt,也不必将行存储在数组中,只需获得我在回答中指出的版本号。您是指优化部分吗?我收到此错误:索引超出了数组的边界,是的,还需要优化部分的帮助我将代码修改为处理格式错误/不感兴趣的行。我得到了这段代码的帮助。非常感谢。尝试优化部分。如果我找不到,我会提出一个问题。你是说优化部分?我得到这个错误:索引超出了数组的界限,是的,我也需要优化部分的帮助。我修改了代码以处理格式错误/不感兴趣的行。我得到了这段代码的帮助。非常感谢。尝试优化部分。如果找不到,我将提出一个问题。我可以将这些行写入另一个文件。但我的第二个问题是我面临的问题。读最后一篇文章的前四个字line@Bala在使用不同的方法访问同一文件之前,必须先关闭读卡器。我可以将这些行写入另一个文件。但我的第二个问题是我面临的问题。读最后一篇文章的前四个字line@Bala在使用不同方法访问同一文件之前,必须先关闭读取器。