我正在通過C#中的Windows窗體選擇帶有文件夾路徑的文本文件,並收集每個路徑的信息。當時,我可以導入文件並僅顯示文本文件中的第二個路徑,但沒有關於該文件夾的信息。這裏是我的代碼:將每行從文本文件放入數組C#
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和自己學習,因爲我寧願學習它而不是給代碼。
謝謝!
@ GuruStron感謝您的支持。這對改善我的答案確實有幫助。 – Anoop