将文本文件读取到数组中
本文关键字:数组 读取 文本 文件 | 更新日期: 2023-09-27 18:24:07
我试图通过将联系人存储在文本文件中来制作联系人簿。例如,假设我有两个名为名字和姓氏的字符串,在文本文件中我有一个名字,在下一行有一个姓氏。这是我目前的代码,但我不确定在do循环中需要做什么,我如何读取一行,将其插入字符串xxx,读取下一行并将其存储在字符串yyy中?
public Contacts[] getAllContacts()
{
List<Contacts> theContactList = new List<Contacts>();
string file_name = "Contacts.txt";
string textLine = "";
if (System.IO.File.Exists(file_name) == true)
{
System.IO.StreamReader objReader;
objReader = new System.IO.StreamReader(file_name);
do
{
objReader.ReadLine() + "'r'n";
} while (objReader.Peek() != 1);
}
if (theContactList.Count > 0)
{
return theContactList.ToArray();
}
else
{
return null;
}
}
我还需要能够在文本文件中存储多个联系人和更多字段,如地址、电话号码等。
在假设总是有2行并且它们具有相同的顺序的情况下,以下代码可以在那里工作:
public Contacts[] getAllContacts()
{
List<Contacts> theContactList = new List<Contacts>();
string file_name = "Contacts.txt";
string textLine = "";
bool firstNameLine = true;
if (System.IO.File.Exists(file_name) == true)
{
System.IO.StreamReader objReader;
objReader = new System.IO.StreamReader(file_name);
Contact newContact;
do
{
textLine = objReader.ReadLine();
if (firstNameLine)
{
newContact = new Contact();
newContact.firstName = textLine;
}
else
{
newContact.sureName = textLine;
theContactList.Add(newContact);
}
firstNameLine = !firstNameLine;
} while (objReader.Peek() != 1);
}
if (theContactList.Count > 0)
{
return theContactList.ToArray();
}
else
{
return null;
}
}
因此,在这种情况下,代码使用了一个布尔变量,该变量定义了使用哪行读取来填充哪个字符串。如果它超过2行(超过2个字符串),则需要一个整数变量(增加+1,然后在读取最后一行时重新设置),而不是IF a switch语句。
最好使用XML或CSV文件,甚至只是一个文本文件,但每个"联系人"都在同一行并解析它们。
下面的代码将执行您想要的操作。
public Contacts[] GetAllContacts()
{
List<Contacts> contacts = new List<Contacts>();
const string filePath = "Contacts.txt";
if (File.Exists(filePath))
{
using (StreamReader sr = new StreamReader(filePath))
{
do
{
Contacts contact = new Contacts();
contact.FirstName = sr.ReadLine();
contact.Surname = sr.ReadLine();
contacts.Add(contact);
} while (sr.Peek() != -1);
}
}
return contacts.ToArray();
}
while (objReader.Peek() != -1)
{
theContactList.Add(new Contact() { Firstname = objReader.ReadLine(), SurName = objReader.ReadLine()});
}
使用初始值设定项列表。(显然对Contact
类成员进行了假设)
使用这个:
string [] file_array = File.ReadAllLines("path");
PS:using System.IO;
该函数读取整个文件并将其行存储在数组中。您可以编辑数组行,然后使用
File.WriteAllLines("path",file_array);
把它们放回文件中。