我有一個文件如下圖所示如何從c#中的文本文件中選取特定的行?
aaaaaaa
ID 12345
David
bbbbbbbbbbb
我的人的ID和姓名
我的輸出應該像
12345
David
莫非
任何人的幫助分開,好嗎?提前致謝。
我有一個文件如下圖所示如何從c#中的文本文件中選取特定的行?
aaaaaaa
ID 12345
David
bbbbbbbbbbb
我的人的ID和姓名
我的輸出應該像
12345
David
莫非
任何人的幫助分開,好嗎?提前致謝。
下面的代碼將幫助您爲這個特殊的問題,試試這個,讓我知道,如果你面對任何困難:
var linesInFile = System.IO.File.ReadAllLines(@"C:\Users\Vishnuraj\Desktop\sample.txt").ToList();
var lineOfID = linesInFile.FirstOrDefault(x => x.ToLower().StartsWith("id"));
if (!String.IsNullOrEmpty(lineOfID))
{
int indexOfID = linesInFile.IndexOf(lineOfID);
if (indexOfID < linesInFile.Count - 1)
{
string nameOfPerson = linesInFile[indexOfID + 1]; // will be "David"
string personId = lineOfID.Substring(3); // will be 12345
}
}
感謝您的幫助 – Bhargav
@Bhargav:很高興聽到。高興地幫助你.......... –
您可以獲取你的ID和名稱如下:
string[]file= File.ReadAllLines(filePath); //Read your text file this way.
int id = 1; //first id will be found at index 1 as mentioned by you.
for (int i = 0; i < file.Length; i++)
{
if (i == id)
{
//here is your id & Name
Console.WriteLine(file[i]);
if (file[id + 1] != null)//checking whether next index if null or not.
Console.WriteLine(file[id + 1]);
id += 4;//incremented as you said, it always be there in a sequence
}
}
您可以進一步修改此代碼,例如將數組轉換爲List
並應用LINQ
等...
如果您NuGet「System.Interact香港專業教育學院」,那麼你可以這樣做:
var lines =
File
.ReadLines(fileName)
.Skip(1)
.Take(2)
.SelectMany(x => x.Split(' ').TakeLast(1))
.ToArray();
var id = lines[0];
var name = lines[1];
是文件的格式記錄?文件中是否有多個數據? 'aaaaaa'和'bbbbb'的意義是什麼? – Dai
每次都會有相同位置的名稱和號碼? – Pavvy
@戴是文件中有多行,我提到了aaa和bbb而不是文件中的不同行 – Bhargav