将文本文件中的每一行放入数组 C#
本文关键字:一行 数组 文件 文本 | 更新日期: 2024-10-26 05:53:11
我正在努力通过 C# 中的 Windows 表单选择带有文件夹路径的文本文件,并收集有关每个路径的信息。 目前,我可以导入文件并仅显示文本文件中的第二个路径,但不显示有关文件夹的信息。 这是我的代码:
private void btnFilePath_Click(object sender, EventArgs e)
{
//creating a stream and setting its value to null
Stream myStream = null;
//allowing the user select the file by searching for it
OpenFileDialog open = new OpenFileDialog();
open.InitialDirectory = "c:''";
open.Filter = "txt files (*.txt)|*.txt";
open.FilterIndex = 2;
open.RestoreDirectory = true;
//if statement to print the contents of the file to the text box
if (open.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = open.OpenFile()) != null)
{
using (myStream)
{
txtFilePath.Text = string.Format("{0}", open.FileName);
if (txtFilePath.Text != "")
{
lstFileContents.Text = System.IO.File.ReadAllText(txtFilePath.Text);
//counting the lines in the text file
using (var input = File.OpenText(txtFilePath.Text))
{
while (input.ReadLine() != null)
{
//getting the info
lstFileContents.Items.Add("" + pathway);
pathway = input.ReadLine();
getSize();
getFiles();
getFolders();
getInfo();
result++;
}
MessageBox.Show("The number of lines is: " + result, "");
lstFileContents.Items.Add(result);
}
}
else
{
//display a message box if there is no address
MessageBox.Show("Enter a valid address.", "Not a valid address.");
}
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read the file from disk. Original error: " + ex.Message);
}
}
}
我在想使用 foreach 将每一行复制到变量中,或者将每行放入数组中并循环访问它以收集信息。
谁能告诉我哪个最合适,这样我就可以去 MSDN 自己学习,因为,我宁愿学习它而不是得到代码。
谢谢!
我不确定你的问题是什么,因为你似乎已经回答了它。如果您希望我们对其进行审查,您的问题将更适合代码审查:https://codereview.stackexchange.com/
如果要使用 MSDN,请查看此处:http://msdn.microsoft.com/en-us/library/System.IO.File_methods(v=vs.110).aspx
剧透警告,这是我的做法:
string[] lines = null;
try
{
lines = File.ReadAllLines(path);
}
catch(Exception ex)
{
// inform user or log depending on your usage scenario
}
if(lines != null)
{
// do something with lines
}
将所有行收集到数组中,我会使用
var lines = File.ReadAllLines(path);
如果你想有更多的参考而不是答案本身,请逐个获取这些链接,所有这些链接都以不同的方式解释事物。
C# File.ReadLines
如何:从文本文件中读取(C# 编程指南)
如何:一次读取一行文本文件 (Visual C#)
希望它能帮助您了解有关 C# 中的文件 IO 操作的更多信息。