簡體   English   中英

需要從文本文件C#中獲取特定的文本行

[英]Need to get Specific lines of text from a text file C#

我有一個看起來像這樣的文本文件:

DeltaV User List - 17 Jun 2013
SUPPLY_CHAIN


UserID              Full Name
BAINC               C M B
BEEMANH             H B
CERIOJI             J M C
LADUCK              K L
MAYC                C M
NEWTONC             C N

DeltaV User List - 17 Jun 2013
FERM_OPER


UserID              Full Name
POULIOTM            M P
TURNERM7            M T

我需要為C#中的每個部分獲取單獨的用戶,但我不確定該怎么做。 我使用的是StreamReader類,它用於獲取Area名稱(全部大寫的單詞),但似乎無法獲得所有用戶。 我有一個包含2個字符串Name&Area的用戶類,並且試圖創建一個用戶對象列表。

到目前為止,這是我嘗試過的操作:(我在代碼前面聲明了User對象的列表)

        // read user list text file
        var userReader = new StreamReader(File.OpenRead(UserListPath));

        while(!userReader.EndOfStream)
        {
            var line = userReader.ReadLine();
            var newUser = new User();
            if(line.Contains("DeltaV User List"))
            {
                var Area = userReader.ReadLine();
                newUser.Area = Area;
                userReader.ReadLine();
                userReader.ReadLine();
                userReader.ReadLine();

                var userid = userReader.ReadLine();
                Console.WriteLine(userid);
                var name = userid.Split(' ');
                Console.WriteLine(name[0]);
                newUser.UserId = name[0];
            }
            Users.Add(newUser);
        }

哦,我只需要獲取UserId,也不需要全名。

已編輯

這是一小段代碼,應該可以滿足您的需求:

        using (var fileStream = File.OpenRead(UserListPath))
        using (var userReader = new StreamReader(fileStream))
        {
            string currentArea = string.Empty;
            string currentToken = string.Empty;
            while (!userReader.EndOfStream)
            {
                var line = userReader.ReadLine();
                if (!string.IsNullOrEmpty(line))
                {
                    var tokenFound = Tokens.FirstOrDefault(x => line.StartsWith(x));
                    if (string.IsNullOrEmpty(tokenFound))
                    {
                        switch (currentToken)
                        {
                            case AreaToken:
                                currentArea = line.Trim();
                                break;
                            case UserToken:
                                var array = line.Split(' ');
                                if (array.Length > 0)
                                {
                                    Users.Add(new User()
                                    { 
                                        Name = array[0],
                                        Area = currentArea
                                    });
                                }
                                break;
                            default:
                                break;
                        }
                    }
                    else
                    {
                        currentToken = tokenFound;
                    }
                }
            }
        }

該程序假定您的輸入文件以換行符結尾。 它使用您必須在類中或所需的任何地方通過修改它們的訪問器(例如, privatepublic )來聲明的常量:

private const string AreaToken = "DeltaV";
private const string UserToken = "UserID";

private List<string> Tokens = new List<string>() { AreaToken, UserToken };

當然,我已經按照自己的方式做了,可能有很多更好的方法。 以您想要的方式對其進行改進,它只是一種可以編譯和工作的草稿。

除其他外,您會注意到:

  • 使用using關鍵字,這對於確保您的內存/資源/文件句柄正確可用非常有用。
  • 我試圖避免使用硬編碼值(這就是為什么我使用常量和引用列表的原因)
  • 我試圖做到這一點,所以您只需要在Token引用列表(稱為Tokens )中添加新的常量,並擴展切換用例以處理新的文件Token /場景

最后,不要忘記實例化您的User列表:

List<User> Users = new List<User>();

這是我的工作:

void Main()
{
    var filePath = @"..."; //insert your file path here
    var lines = File.ReadLines(filePath); //lazily read and can be started before file is fully read if giant file

    IList<User> users = new List<User>();
    var Area = string.Empty;
    foreach(var line in lines)
    {
       if(string.IsNullOrWhiteSpace(line) || 
           line.Contains("DeltaV User List") ||
           line.Contains("UserID")
          )
       {
          continue;
       }


    var values = line.Split(' ');
    if(values.Length == 1)
    {
          Area = values[0];
          continue;
    }

    var currentUser = new User
    {
          Name = values[0],
          Area = Area
    };
    users.Add(currentUser);
  }
    users.Dump("User List"); //Dump is a Linqpad method to display result see screen shot
}

// Define other methods and classes here
public class User
{
    public string Name { get; set; }
    public string Area { get; set; }
}

您發布的文件的結果: 用戶結果

File.ReadLines

LinqPad用於測試小的代碼片段。

您可以將其復制並粘貼到LinqPad中,以根據需要進行修改,只需為其提供一個文件即可。

    // read user list text file
    var userReader = new StreamReader(File.OpenRead(UserListPath));
    var Area = "";
    while(!userReader.EndOfStream)
    {
        var line = userReader.ReadLine();
        if(line.Contains("DeltaV User List"))
        {
            Area = userReader.ReadLine();  // Area applies to group of users below.
            userReader.ReadLine(); // blank line
            userReader.ReadLine(); // blank line
            userReader.ReadLine(); // User ID header line
        }
        else
        {
            if (line.trim() != "") // Could be blank line before "DeltaV..." 
            {
                var userid = line;
                var newUser = new User();
                newUser.Area = Area;
                // I left the following lines in place so that you can test the results.
                Console.WriteLine(userid);
                var name = userid.Split(' ');
                Console.WriteLine(name[0]);
                newUser.UserId = name[0];
                Users.Add(newUser);
            }
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM