随机访问CSV文件中的指定记录

时间:2014-02-12 03:45:36

标签: c# csv random-access

此代码可以正常工作:

            string[] lineOfContents = File.ReadAllLines(@"C:\users.csv");
            foreach (var line in lineOfContents)
            {
                string[] tokens = line.Split(',');
                if (tokens[2] == "ed@yahoo.com")
                {                    
                    MessageBox.Show("Email already exists");
                }
               else
               {
                   MessageBox.Show("Ok");
               }
            }

以上代码的工作原理如下: enter image description here

所以,我想用简单的代码对CSV文件中的“电子邮件”记录进行“直接访问”,如下所示: enter image description here

2 个答案:

答案 0 :(得分:4)

string fileContents = File.ReadAllText("c:\\users.csv");

if (fileContents.Contains("ed@yahoo.com")) {
    MessageBox.Show("Email already exists");
} else {
    MessageBox.Show("Ok");
}

答案 1 :(得分:1)

一种方法可以是:

string[] lineOfContents = File.ReadAllLines(@"C:\users.csv");
string email="ed@yahoo.com";
if (lineOfContents.Contains(email))
{  
    MessageBox.Show("Email already exists");
}
else
{
    MessageBox.Show("Ok");
}

使用linq的其他方式可以是:

string[] lineOfContents = File.ReadAllLines(@"C:\users.csv");
string email="ed@yahoo.com";
if(lineOfContents.Any(e->e.Contains(email))){...}

还有一个:

string temp = "";
if(String.Join(temp,lineOfContents).Contains(email);

另一个或最佳可以是:

if (Array.IndexOf(lineOfContents, email) >= 0)
{
    //Your stuff goes here
}

我很害怕,你问的是什么(“..是否有可能避免阅读所有文件内容,我更愿意直接去”电子邮件“”)不可能开箱即用。但是有一些很好的实用工具可以帮助你更有效地工作(但我怀疑他们不会解析文件)。

一些好的是:

  • A Fast CSV Reader
  • CsvHelper(Nuget包)
  • Microsoft的另一个好消息是TextFieldParser Class

    • TextFieldParser对象提供了解析结构化文本文件的方法和属性。使用TextFieldParser解析文本文件类似于迭代文本文件,而提取文本字段的ReadFields方法类似于拆分字符串。

      TextFieldParser可以解析两种类型的文件:分隔固定宽度。某些属性(如Delimiters和HasFieldsEnclosedInQuotes)仅在使用分隔文件时才有意义,而FieldWidths属性仅在使用固定宽度文件时才有意义。

相关问题