【问题标题】:Opening multiple files in C# and checking the contents of every file在 C# 中打开多个文件并检查每个文件的内容
【发布时间】:2012-06-20 13:56:26
【问题描述】:

我想要做的是打开多个文件并从每个文件中读取文本并检查某些关键字并将它们全部打印到一个新文件中,一旦完成,将使用所有关键字创建一个新文件。我已经在使用 foreach 来遍历所有文件名,并且我知道如何打开多个文件,但是在同时打印的同时检索内容并检查某些条件呢?

以下只是我目前所拥有的一个示例,非常标准的东西。

谢谢大家!

  if (dr == System.Windows.Forms.DialogResult.OK)
        {
            // Read the files
            foreach (String file in openFileDialog1.FileNames)
            {

                try
                {

                    listView1.Items.Add(file);

                }
                catch (SecurityException ex)
                {
                    // The user lacks appropriate permissions to read files, discover paths, etc.
                    MessageBox.Show("Security error. Please contact your administrator for details.\n\n" +
                        "Error message: " + ex.Message + "\n\n" +
                        "Details (send to Support):\n\n" + ex.StackTrace
                    );
                }
                catch (Exception ex)
                {
                    // Could not load the image - probably related to Windows file system permissions.
                    MessageBox.Show("Cannot display the image: " + file.Substring(file.LastIndexOf('\\'))
                        + ". You may not have permission to read the file, or " +
                        "it may be corrupt.\n\nReported error: " + ex.Message);
                }

            }

        }

【问题讨论】:

  • 这应该被标记为作业吗?

标签: c# winforms openfiledialog


【解决方案1】:

要读取文件,请使用System.IO.File.ReadAllText()。这会将所有内容放入一个字符串变量中。

【讨论】:

    【解决方案2】:

    您像 SoMoS 建议的那样使用 System.IO.File.ReadAllText() 读取文件。 Search the string in whatever way works best 并使用 StreamWriter 写回数据

    【讨论】:

    • 谢谢哥们,我很感激!
    【解决方案3】:
    Try
                Using sr As New StreamReader("TestFile.txt")
                    Dim line As String
                    Do
                        line = sr.ReadLine()
                        If Not (line Is Nothing) Then
                           Console.WriteLine(line)
                        End If
                    Loop Until line Is Nothing
                End Using
            Catch e As Exception
                Console.WriteLine("The file could not be read:")
                Console.WriteLine(e.Message)
            End Try
    

    ;)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-05
      • 2013-02-14
      • 2021-03-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-21
      • 1970-01-01
      相关资源
      最近更新 更多