简体   繁体   English

C#读取文本文件中列中的每个单词

[英]C# reading each word in column in a text file

I've got a problem when I wanted to read and compare each word in my column based text file. 当我想阅读和比较基于列的文本文件中的每个单词时遇到问题。

Here is how my file looks like: 这是我的文件的样子:

[ID]    [Uname] [PW]    [Email]    
0       asd     asd     s   
1       asdd    asd     asd@asd 
2       asd     asd     asd@

I want to read and compare each word in the second column with my textbox's text. 我想阅读第二列中的每个单词并将其与文本框的文本进行比较。 If any of them equals with the textbox's text,it would say "The username has taken." 如果它们中的任何一个等于文本框的文本,则会显示“用户名已被占用”。

This is the code what i've tried: 这是我尝试过的代码:

string[] lines = File.ReadAllLines(path);
                foreach (var line in lines) { 
                 var firstValue = line.Split(new string[] { "\t" },StringSplitOptions.RemoveEmptyEntries);
                 Console.WriteLine(firstValue); 
                 if (firstValue[1].Equals(txt_uname.Text) && txt_uname.Text != "") {}
    }

The problem is that the "if" checks only the last element(asd) of my [Uname] column 问题是“ if”仅检查我的[Uname]列的最后一个元素(asd)

Since you are reading in all the lines at once, this would also work for you. 由于您正在一次阅读所有行,因此这也对您有用。

string[] lines = File.ReadAllLines(path);
if (!String.IsNullOrEmpty(txt_uname.Text) 
     && lines.Where(u => u.Split(new string[] { "\t" }, StringSplitOptions.RemoveEmptyEntries)[1].Equals(txt_uname.Text)).Count() > 0)
{ }

Also it sounds like this is the code you're actually using: 也听起来这是您实际使用的代码:

string[] lines = File.ReadAllLines("FilePath");
        foreach (var line in lines)
        {
            var firstValue = line.Split(new[] { "\t" }, StringSplitOptions.RemoveEmptyEntries);
            Console.WriteLine(firstValue[1]); // Needs to have [1] or it will just print System.String[]
        }

Even then, this should work. 即使这样,这也应该起作用。 So we must not be seeing the bigger picture or your file is missing tabs and using spaces as well. 因此,我们一定不能看到更大的图片,否则您的文件将缺少制表符并且也将使用空格。

Here's an example of reading the file line by line (more memory proficient in case a file you are consuming could be in the hundreds of megabytes) and then splitting the lines to values to compare with: 这是一个逐行读取文件的示例(如果您正在使用的文件可能在数百兆字节内,则可以更熟练地使用内存),然后将这些行拆分为多个值以进行比较:

using (var streamReader = new StreamReader("FilePath"))
        {
            if (!streamReader.EndOfStream)
            {
                string line = streamReader.ReadLine();

                if (!String.IsNullOrEmpty(line))
                {
                    string[] splitValues = line.Split(new[] { "\t" }, StringSplitOptions.RemoveEmptyEntries);

                    if (splitValues[1] == txt_uname.Text)
                    {
                        // Stuff
                    }
                }
            }
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM