Answer the question
In order to leave comments, you need to log in
C#: How to properly read and write objects to an ArrayList?
Hello!
How to properly read and write objects to ArrayList?
String[] substrings = null;
ArrayList aL = new ArrayList();
public void toSay(string s)
{
Char delimiter = '|';
substrings = s.Split(delimiter);
ArrayList aaa = new ArrayList();
for (int i =0; i < substrings.Length; i++)
{
aaa.Add(substrings[i]);
}
aL.Add(aaa);
}
public void Click_OpenFile()
{
int counter = 0;
string line;
string result = form1.OpenFie();
System.IO.StreamReader file = new System.IO.StreamReader(result);
while ((line = file.ReadLine()) != null)
{
toSay(line);
counter++;
}
file.Close();
for (int i = 0; i < aL.Count; i++) {
MessageBox.Show(aL[i].ToString());
}
Answer the question
In order to leave comments, you need to log in
Do not use ArrayList
unless absolutely necessary. Therefore, the compiler failed to warn you that it ArrayList
consists of ArrayList
's, in which strings (a two-dimensional array of strings) and not just strings.
Instead ArrayList
, you must use a typed dynamic array List<string>
.
public void Click_OpenFile()
{
string fileName = form1.OpenFie();
IList<string[]> aL = ParseFile(fileName);
foreach (var line in aL)
{
// Снова собираем токены в строки
MessageBox.Show(string.Join(" ", line));
}
}
// Читаем файл и построчно парсим его
private IList<string[]> ParseFile(string fileName)
{
if (string.IsNullOrEmpty(fileName))
{
throw new ArgumentNullException(nameof(fileName));
}
if (!File.Exists(fileName))
{
throw new ArgumentException($"There is no file {fileName}!");
}
string[] fileContent = File.ReadAllLines(result);
var aL = new List<string[]>(fileContent.Length);
foreach (var line in fileContent)
{
aL.Add(ParseString(line));
}
return aL;
}
// Разбиваем строки на токены
private string[] ParseString(string s)
{
const char delimiter = '|';
return s.Split(delimiter);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question