[.net] C# writing to a text file

Started by
3 comments, last by daniel_i_l 17 years, 6 months ago
I want to write the contents of an ArrayList to a txt file. I did this:

private void SavePaths()
        {
            FileStream file = new FileStream("playlist2.txt",  
            FileMode.OpenOrCreate, FileAccess.Write);
            StreamWriter output = new StreamWriter(file);
            output.WriteLine("hello");
            output.WriteLine("{0}", Path.Count);
            for (int i = 0; i < Path.Count; ++i)
            {
                output.WriteLine("next");
                output.WriteLine(Path.ToString());
            }
            
            output.Close();
            file.Close();
        }

it compiles without errors but when i tell it to write to a file it doesn't do anything. it doesn't even open the file if i don't put it there by myself. and when i do put it there it just writes "hello" then "0" - regardless of the length of the AL. What did i do wrong? Thanks.
"We've all heard that a million monkeys banging on a million typewriters will eventually reproduce the entire works of Shakespeare. Now, thanks to the internet, we know this is not true." -- Professor Robert Silensky
Advertisement
To write an ArrayList to a file, I'd prefer to do the following:
// Make the array listArrayList arrayList= new ArrayList();arrayList.Add("Hello");arrayList.Add("World");// Write it to a fileusing(StreamWriter writer = new StreamWriter("playlist2.txt", false))    foreach(object s in arrayList)        writer.WriteLine(s.ToString());
Rob Loach [Website] [Projects] [Contact]
Seems to work fine for me - what version of the framework are you using?

Alex
This is probably something really stupid to do with the (global) Path; the code looks fine, and the displayed 0 (for the count) shows that's where the problem lies. A method like this shouldn't be using a global anyway, you should pass the list in as a parameter.

Rob's code is neater (foreach loops are great!) but yours should work.
I found the problem - before saving the files i opened media files with an open dialog box, then when i opened the playlist for writing it made a new txt file in the same folder that had the media, to solve this i enabled "restore directory" in the ODB and it worked fine.
Thanks everyone!
"We've all heard that a million monkeys banging on a million typewriters will eventually reproduce the entire works of Shakespeare. Now, thanks to the internet, we know this is not true." -- Professor Robert Silensky

This topic is closed to new replies.

Advertisement