从目录c#中的文件中的特定行读取行

时间:2023-02-06 12:20:39

this code works fine but my problem is that i need to read the files that contains ESSD and if this file contains a name in certain line, add it to my listbox1, and if it doesnt contain the name in that line, dont add it to the listbox1.

这段代码工作正常,但我的问题是我需要读取包含ESSD的文件,如果这个文件包含某个行中的名称,请将其添加到我的listbox1,如果它不包含该行中的名称,则不要将其添加到listbox1。

Thanks.

谢谢。

private void button1_Click(object sender, EventArgs e)
    {
        DialogResult result = this.openFileDialog1.ShowDialog();
        if (result == DialogResult.OK)
        {
            string[] Nomarchivo = this.openFileDialog1.FileNames;
            string NomDirec = Path.GetDirectoryName(Nomarchivo[0]);
            for (int a = 0; a <= Nomarchivo.Length - 1; a++)
            {
                string NomDirGral = Nomarchivo[a].Remove(Nomarchivo[a].Length - 7, 7);
                string NomGral = NomDirGral.Replace(NomDirec, " ");
                NomGral = NomGral.Remove(0, 2);
                foreach (string f in Directory.GetFiles(NomDirec, NomGral + "*"))
                    this.listBox1.Items.Add(f);
                foreach (string h in Directory.GetFiles(NomDirec, "resume*"))
                    this.listBox1.Items.Add(h);
                foreach (string t in Directory.GetFiles(NomDirec, "ESSD1*"))
                    this.listBox1.Items.Add(t);
            }
            string[] list1 = new string[listBox1.Items.Count];
            for (int b = 0; b <= listBox1.Items.Count - 1; b++)
            {
                list1[b] = listBox1.Items[b].ToString();
            }
            string[] list2 = list1.Distinct().ToArray();
            foreach (string g in list2)
                this.listBox2.Items.Add(g);

            Class1 arr1 = new Class1();
            arr1.array(listBox2);
        }
        else { Close(); }
    }

3 个解决方案

#1


0  

.NET 4 offers a nice function called File.ReadLines(fileName)

.NET 4提供了一个很好的函数FileReadLines(fileName)

With this function, your above code can be modified as:

使用此功能,您可以将上述代码修改为:

private void button1_Click(object sender, EventArgs e) 
{ 
    DialogResult result = this.openFileDialog1.ShowDialog(); 
    if (result == DialogResult.OK) 
    { 
        string[] Nomarchivo = this.openFileDialog1.FileNames; 
        string NomDirec = Path.GetDirectoryName(Nomarchivo[0]); 
        for (int a = 0; a <= Nomarchivo.Length - 1; a++) 
        { 

            //the name we are looking for.
            List<string> namesWeAreLookingFor = new List<string>();

            string NomDirGral = Nomarchivo[a].Remove(Nomarchivo[a].Length - 7, 7); 
            string NomGral = NomDirGral.Replace(NomDirec, " "); 
            NomGral = NomGral.Remove(0, 2); 
            foreach (string f in Directory.GetFiles(NomDirec, NomGral + "*")) 
                this.listBox1.Items.Add(f); 
            foreach (string h in Directory.GetFiles(NomDirec, "resume*")) 
            {
                this.listBox1.Items.Add(h); 

                var nameLines = File.ReadLines(NomDirec + @"\" + h);
                foreach (var item in nameLines)
                {
                    //do whatever you need to get a name in this file here
                    //...

                    //Assuming there is one name per line, add the name to the list
                    namesWeAreLookingFor.Add(item);
                }
            }
            foreach (string t in Directory.GetFiles(NomDirec, "ESSD1*")) 
            {
                this.listBox1.Items.Add(t); 
                //try to access the file so we can read line 6 using new .NET 4 method 
                var lines = File.ReadLines(NomDirec + @"\" + t);

                //see if we even have 6 lines
                if (lines.Count() < 6)
                    continue;

                String line6 = lines.ElementAt(5);

                //loop through the names we pulled
                foreach (var item in namesWeAreLookingFor)
                {
                    //see if line 6  containes that name.
                    if (line6.Contains(item))
                    {
                        //if it exists, then add it to the list and exit the loop.
                        this.listBox1.Items.Add(t);
                        break;
                    }
                }
            }
        } 
        string[] list1 = new string[listBox1.Items.Count]; 
        for (int b = 0; b <= listBox1.Items.Count - 1; b++) 
        { 
            list1[b] = listBox1.Items[b].ToString(); 
        } 
        string[] list2 = list1.Distinct().ToArray(); 
        foreach (string g in list2) 
            this.listBox2.Items.Add(g); 

        Class1 arr1 = new Class1(); 
        arr1.array(listBox2); 
    } 
    else { Close(); } 

#2


0  

Here's two ways:

这有两种方式:

public static string ReadSpecificLine1( string path , int lineNumber )
{
  int cnt = 0 ;
  string desiredLine = File.ReadAllLines( path ).FirstOrDefault( x => (++cnt == lineNumber) ) ;
  return desiredLine ;
}

public static string ReadSpecificLine2( string path , int lineNumber )
{
  string desiredLine = null ;
  using ( FileStream   stream = new FileStream( path , FileMode.Open , FileAccess.Read , FileShare.Read ) )
  using ( StreamReader reader = new StreamReader( stream ) )
  {
    int    i           = 0    ;
    string line        = null ;
    while ( null != (line=reader.ReadLine()) && ++i < lineNumber )
    {
    }
    if ( i == lineNumber && line != null )
    {
       desiredLine = line ;
    }
    return desiredLine ;
  }
}

If you know for certain that your file

如果您确定知道您的文件

  • Contains only characters that comprise a single, fixed-size Unicode code unit in the file's unicode encoding scheme, and

    仅包含在文件的unicode编码方案中包含单个固定大小的Unicode代码单元的字符,以及

  • has fixed length lines (records)

    有固定长度的行(记录)

Then you can seek() directly to the line in question, as in this example using UTF-16 encoding, thus saving extraneous I/O operations:

然后你可以直接搜索()直到相关的行,就像在这个例子中使用UTF-16编码一样,从而节省了无关的I / O操作:

public static string ReadSpecificLineFromUTF16EncodedFile( string path , int lineNumber )
{
  string    desiredLine                    = null ;

  using ( FileStream   stream = new FileStream( path , FileMode.Open , FileAccess.Read , FileShare.Read ) )
  using ( StreamReader reader = new StreamReader( stream , Encoding.Unicode ) )
  {
    Encoding  UTF_16                         = Encoding.Unicode ;
    const int RECORD_LENGTH_IN_CHARS         = 80 ;
    const int FIXED_CODE_UNIT_SIZE_IN_OCTETS = sizeof(char) ; // size of a UTF-16 code unit (char) in octets
    const int RECORD_LENGTH_IN_OCTETS        = RECORD_LENGTH_IN_CHARS * FIXED_CODE_UNIT_SIZE_IN_OCTETS ;

    long offset = (lineNumber-1)*RECORD_LENGTH_IN_OCTETS ;

    if ( offset <  0 ) throw new ArgumentOutOfRangeException("lineNumber") ;
    if ( offset <= stream.Length )
    {
      stream.Seek( offset , SeekOrigin.Begin ) ;
      desiredLine = reader.ReadLine() ;
    }
  }
  return desiredLine ;
}

Note that this will only work if the above two conditions are true.

请注意,这仅在以上两个条件为真时才有效。

#3


0  

Well the problem is that i want to access the ESSD file and the read line 6, if this line contains a name that is stored in the Resume file, send the ESSD file to listbox1, and if not, doesnt add ESSD to my listbox1

那么问题是我想访问ESSD文件和读取行6,如果这行包含存储在Resume文件中的名称,则将ESSD文件发送到listbox1,如果没有,则不会将ESSD添加到我的listbox1

So:

所以:

  1. Read/Parse the resume file
  2. 读取/解析恢复文件
  3. Sort the Resume list.
  4. 对“继续”列表进行排序。
  5. Create a list of all the ESSD files
  6. 创建所有ESSD文件的列表
  7. Iterate through said list reading "Line 6" from each file
  8. 通过从每个文件读取“第6行”的列表进行迭代
  9. search resume file for name in "Line 6"
  10. 在“第6行”中搜索名称的简历文件
  11. Add if found
  12. 添加如果找到

Try to add that into your above code and see what happens. See how it goes and revise your question maybe.

尝试将其添加到上面的代码中,看看会发生什么。看看它如何发展并修改你的问题。

#1


0  

.NET 4 offers a nice function called File.ReadLines(fileName)

.NET 4提供了一个很好的函数FileReadLines(fileName)

With this function, your above code can be modified as:

使用此功能,您可以将上述代码修改为:

private void button1_Click(object sender, EventArgs e) 
{ 
    DialogResult result = this.openFileDialog1.ShowDialog(); 
    if (result == DialogResult.OK) 
    { 
        string[] Nomarchivo = this.openFileDialog1.FileNames; 
        string NomDirec = Path.GetDirectoryName(Nomarchivo[0]); 
        for (int a = 0; a <= Nomarchivo.Length - 1; a++) 
        { 

            //the name we are looking for.
            List<string> namesWeAreLookingFor = new List<string>();

            string NomDirGral = Nomarchivo[a].Remove(Nomarchivo[a].Length - 7, 7); 
            string NomGral = NomDirGral.Replace(NomDirec, " "); 
            NomGral = NomGral.Remove(0, 2); 
            foreach (string f in Directory.GetFiles(NomDirec, NomGral + "*")) 
                this.listBox1.Items.Add(f); 
            foreach (string h in Directory.GetFiles(NomDirec, "resume*")) 
            {
                this.listBox1.Items.Add(h); 

                var nameLines = File.ReadLines(NomDirec + @"\" + h);
                foreach (var item in nameLines)
                {
                    //do whatever you need to get a name in this file here
                    //...

                    //Assuming there is one name per line, add the name to the list
                    namesWeAreLookingFor.Add(item);
                }
            }
            foreach (string t in Directory.GetFiles(NomDirec, "ESSD1*")) 
            {
                this.listBox1.Items.Add(t); 
                //try to access the file so we can read line 6 using new .NET 4 method 
                var lines = File.ReadLines(NomDirec + @"\" + t);

                //see if we even have 6 lines
                if (lines.Count() < 6)
                    continue;

                String line6 = lines.ElementAt(5);

                //loop through the names we pulled
                foreach (var item in namesWeAreLookingFor)
                {
                    //see if line 6  containes that name.
                    if (line6.Contains(item))
                    {
                        //if it exists, then add it to the list and exit the loop.
                        this.listBox1.Items.Add(t);
                        break;
                    }
                }
            }
        } 
        string[] list1 = new string[listBox1.Items.Count]; 
        for (int b = 0; b <= listBox1.Items.Count - 1; b++) 
        { 
            list1[b] = listBox1.Items[b].ToString(); 
        } 
        string[] list2 = list1.Distinct().ToArray(); 
        foreach (string g in list2) 
            this.listBox2.Items.Add(g); 

        Class1 arr1 = new Class1(); 
        arr1.array(listBox2); 
    } 
    else { Close(); } 

#2


0  

Here's two ways:

这有两种方式:

public static string ReadSpecificLine1( string path , int lineNumber )
{
  int cnt = 0 ;
  string desiredLine = File.ReadAllLines( path ).FirstOrDefault( x => (++cnt == lineNumber) ) ;
  return desiredLine ;
}

public static string ReadSpecificLine2( string path , int lineNumber )
{
  string desiredLine = null ;
  using ( FileStream   stream = new FileStream( path , FileMode.Open , FileAccess.Read , FileShare.Read ) )
  using ( StreamReader reader = new StreamReader( stream ) )
  {
    int    i           = 0    ;
    string line        = null ;
    while ( null != (line=reader.ReadLine()) && ++i < lineNumber )
    {
    }
    if ( i == lineNumber && line != null )
    {
       desiredLine = line ;
    }
    return desiredLine ;
  }
}

If you know for certain that your file

如果您确定知道您的文件

  • Contains only characters that comprise a single, fixed-size Unicode code unit in the file's unicode encoding scheme, and

    仅包含在文件的unicode编码方案中包含单个固定大小的Unicode代码单元的字符,以及

  • has fixed length lines (records)

    有固定长度的行(记录)

Then you can seek() directly to the line in question, as in this example using UTF-16 encoding, thus saving extraneous I/O operations:

然后你可以直接搜索()直到相关的行,就像在这个例子中使用UTF-16编码一样,从而节省了无关的I / O操作:

public static string ReadSpecificLineFromUTF16EncodedFile( string path , int lineNumber )
{
  string    desiredLine                    = null ;

  using ( FileStream   stream = new FileStream( path , FileMode.Open , FileAccess.Read , FileShare.Read ) )
  using ( StreamReader reader = new StreamReader( stream , Encoding.Unicode ) )
  {
    Encoding  UTF_16                         = Encoding.Unicode ;
    const int RECORD_LENGTH_IN_CHARS         = 80 ;
    const int FIXED_CODE_UNIT_SIZE_IN_OCTETS = sizeof(char) ; // size of a UTF-16 code unit (char) in octets
    const int RECORD_LENGTH_IN_OCTETS        = RECORD_LENGTH_IN_CHARS * FIXED_CODE_UNIT_SIZE_IN_OCTETS ;

    long offset = (lineNumber-1)*RECORD_LENGTH_IN_OCTETS ;

    if ( offset <  0 ) throw new ArgumentOutOfRangeException("lineNumber") ;
    if ( offset <= stream.Length )
    {
      stream.Seek( offset , SeekOrigin.Begin ) ;
      desiredLine = reader.ReadLine() ;
    }
  }
  return desiredLine ;
}

Note that this will only work if the above two conditions are true.

请注意,这仅在以上两个条件为真时才有效。

#3


0  

Well the problem is that i want to access the ESSD file and the read line 6, if this line contains a name that is stored in the Resume file, send the ESSD file to listbox1, and if not, doesnt add ESSD to my listbox1

那么问题是我想访问ESSD文件和读取行6,如果这行包含存储在Resume文件中的名称,则将ESSD文件发送到listbox1,如果没有,则不会将ESSD添加到我的listbox1

So:

所以:

  1. Read/Parse the resume file
  2. 读取/解析恢复文件
  3. Sort the Resume list.
  4. 对“继续”列表进行排序。
  5. Create a list of all the ESSD files
  6. 创建所有ESSD文件的列表
  7. Iterate through said list reading "Line 6" from each file
  8. 通过从每个文件读取“第6行”的列表进行迭代
  9. search resume file for name in "Line 6"
  10. 在“第6行”中搜索名称的简历文件
  11. Add if found
  12. 添加如果找到

Try to add that into your above code and see what happens. See how it goes and revise your question maybe.

尝试将其添加到上面的代码中,看看会发生什么。看看它如何发展并修改你的问题。