我有以下行的文本文件(比如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
現在,我想寫所有以「相對」兩個字到一個文本文件(比如text2.txt)線。所以我text2.txt應該是這樣的:
4410 Rel testRel1
4412 Rel testRel2
4413 Rel testRel3
4414 Rel testRel4
4415 Rel testRel5
Atlast,我的代碼應該閱讀text2.txt的前四個字符返回text2.txt採取text1.txt的路徑作爲輸入的最後一行(即4415)的。 以下是我的代碼。可能是我可能寫了一半,不知道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是一個臨時文件,用於實現上面指定的。 – Bala
您不必創建'file2.txt',也不需要將行存儲在數組中,只是爲了獲取內部編號,正如我在答案中指出的那樣。 – twoflower