我想要做的是打开多个文件并读取每个文件的文本并检查某些关键字并将它们全部打印到一个新文件中,一旦完成,将创建一个包含所有关键字的新文件。我已经使用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);
}
}
}
答案 0 :(得分:1)
要阅读文件,请使用System.IO.File.ReadAllText()
。这会将所有内容放入字符串变量中。
答案 1 :(得分:0)
您使用System.IO.File.ReadAllText()读取文件,如SoMoS建议的那样。 Search the string in whatever way works best并使用StreamWriter
将数据写回答案 2 :(得分:0)
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
)