【问题标题】:c# split line with .txtc# 用.txt分割行
【发布时间】:2011-03-11 20:33:30
【问题描述】:

假设我在名为 users.txt 的 txt 文件中有 5 行,每行包含以下信息

用户名:密码

我将如何拆分 txt 文件中的每一行并将用户名存储为一个字符串,密码存储为另一个。

我有使用此代码抓取随机行的代码。此代码也用于我项目的另一部分,因此我不希望更改代码。我在想在线路被抓住后调用另一个函数,但我不知道如何用 : 分割它:

private static string GetRandomLine(string file)
    {
        List<string> lines = new List<string>();

        Random rnd = new Random();

        int i = 0;


        try
        {
            if (File.Exists(file))
            {
                //StreamReader to read our file
                StreamReader reader = new StreamReader(file);

                //Now we loop through each line of our text file
                //adding each line to our list
                while (!(reader.Peek() == -1))
                    lines.Add(reader.ReadLine());

                //Now we need a random number
                i = rnd.Next(lines.Count);

                //Close our StreamReader
                reader.Close();

                //Dispose of the instance
                reader.Dispose();

                //Now write out the random line to the TextBox
                return lines[i].Trim();

            }
            else
            {
                //file doesn't exist so return nothing
                return string.Empty;
            }
        }
        catch (IOException ex)
        {
            MessageBox.Show("Error: " + ex.Message);
            return string.Empty;
        }
    }

【问题讨论】:

  • 听起来这可能是一个课堂练习,所以我会放你一马,但请注意,在现实世界中:永远不要存储这样的密码。
  • 我同意乔尔所说的:-)

标签: c# .net string


【解决方案1】:

你应该可以使用string.Split:

 string line = GetRandomLine(file);
 string[] parts = line.Split(':');

 string user = parts[0];
 string pass = parts[1];

话虽如此,您可能还想添加错误检查(即:确保 parts 有 2 个元素等)。

【讨论】:

    【解决方案2】:

    这更简洁,并且可以处理密码可能包含':'的情况

    当然,我希望您确保密码不是纯文本,并且散列密码不包含任何“:”;但万一他们这样做了,这就是可行的:

    Split() 会导致其他问题。

            bool GetUsernamePassword(string line, ref string uname, ref string pwd)
            {
                int idx = line.IndexOf(':') ;
                if (idx == -1)
                    return false;
                uname = line.Substring(0, idx);
                pwd = line.Substring(idx + 1);
                return true;
            }
    

    .

                string username_password = "username:password";
                string uname = String.Empty;
                string pwd = String.Empty;
                if (!GetUsernamePassword(username_password, ref uname, ref pwd))
                {
                    // Handle error: incorrect format
                }
                Console.WriteLine("{0} {1} {2}", username_password, uname, pwd);
    

    顺便说一句。话虽如此,如果用户名具有“:”,则上述方法将不起作用(与此之前的所有其他解决方案一样):P但这将处理密码具有“:”的情况。

    【讨论】:

      【解决方案3】:

      分割字符串很简单:

      string[] components = myUserAndPass.Split(':'); 
      string userName = components[0];
      string passWord = components[1];
      

      【讨论】:

      • 无需创建new char[] {,因为String.Split 被定义为(params char[] separator) - 请参阅:msdn.microsoft.com/en-us/library/b873y76a.aspx
      • @Reed 你是对的,我在考虑String.Join() 语法;我实际上开始键入 String.Split,然后返回并修复了该部分。 =)
      【解决方案4】:

      【讨论】:

        【解决方案5】:

        使用Split() 方法。 例如,在这种情况下

        string[] info = lines[i].Split(':');

        info[0] 将拥有用户名,info[1] 将拥有密码。

        【讨论】:

          【解决方案6】:

          试试这样的...

          string []split = line.Split(':');

          字符串用户名 = split[0];

          字符串 pwd = split[1];

          【讨论】:

            【解决方案7】:

            Reed Corpsey 已经给出了一个很好的答案,所以我不想给出另一个解决方案,我只想对您的代码发表评论。您可以使用Using 语句来处理为您调用的StreamReader Close 和Dispose 方法。这样,如果发生错误,您不必担心 Stream 处于打开状态。

            稍微改变你的代码会让它看起来像:

            //StreamReader to read our file
            using(StreamReader reader = new StreamReader(file))
            {
                //Now we loop through each line of our text file
                //adding each line to our list
                while (!(reader.Peek() == -1))
                    lines.Add(reader.ReadLine());
            
                //Now we need a random number
                i = rnd.Next(lines.Count);
            }
            //Now write out the random line to the TextBox
            return lines[i].Trim();
            

            【讨论】:

              猜你喜欢
              • 2014-07-16
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2012-10-21
              • 2011-08-29
              • 2012-07-07
              • 2021-03-13
              相关资源
              最近更新 更多