Entwickler-Ecke

IO, XML und Registry - Text in Array


felix96 - Sa 24.09.11 18:49
Titel: Text in Array
Hallo,

ich verzweifle jetzt schon seit Sunden (naja, nicht ganz :-) ) an folgendem Problem:

Ich habe eine Datei, die ich in ein Array bekommen will.
Das ganze soll folgendermaßen aussehen:

Datei:
Zeile1
Zeile2
Zeile3

Array:
1 => Zeile1
2 => Zeile2
3 => Zeile3

(x => ZeileX entspricht array[x])

Hier mal mein aktueller ansatz:

C#-Quelltext
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
private ArrayList ReadFile(string path)
        {
            ArrayList dataList = new ArrayList();
            if (File.Exists(path))
            {
                StreamReader sr = new StreamReader(path);
                string data = sr.ReadToEnd(); sr.Close(); if
                    (!string.IsNullOrEmpty(data))
                {
                    dataList.AddRange(data.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries));
                }
            }
            return dataList;
        }

// ...

arr = (string[]) ReadFile("datei.txt").ToArray(typeof(string));


Wobei hier arr keine Werte enthält :-(

Danke für's lesen

Moderiert von user profile iconChristian S.: Highlight- durch C#-Tags ersetzt


Christian S. - Sa 24.09.11 18:54

Also, erstens ist ArrayList in den allermeisten Fällen nicht zu empfehlen, weil es nicht typensicher ist. Benutze entweder ein richtiges Array, sofern die Länge vorher bekannt ist, oder ansonsten einen List<T>.

Und ansonsten würde ich einfach die ReadAllLines-Methode der File-Klasse benutzen ;-)


C# - Sa 08.10.11 22:38


C#-Quelltext
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
private List<string> ReadFile(string path)
        {
            List<string> dataList = new List<string>();
            if (!File.Exists(path)) return null;
            string data = File.ReadAllLines(path);
            foreach(string s in data.Split('\n''\r')) dataList.Add(s);                 
            return dataList;
        }

// ...

//Entweder
List<string> arr = ReadFile("datei.txt");
//Oder
string[] arr = ReadFile("datei.txt").ToArray();


So müsste es doch eig klappen.


Christian S. - Sa 08.10.11 23:11

ReadAllLines liefert doch schon ein String-Array, Deine Methode wird also weder funktionieren noch ist sie notwendig.


C# - Sa 08.10.11 23:48

Hoppla stimmt ja xD. Ich war bei ReadAllText :oops: mein Fehler.