【发布时间】:2014-03-03 06:46:18
【问题描述】:
我有一个包含以下行的文本文件(比如 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.txt(即 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);
}
}
}
【问题讨论】:
-
如果有任何其他方法,比如将行读取到数组而不是 text2.txt,即使这样也有帮助。我的 text2.txt 是用于实现上述指定的临时文件。
-
您不必创建
file2.txt也不必将行存储在数组中,只是为了获得我在回答中指出的内部版本号。