Sign in to follow this  
daniel_i_l

[.net] C# writing to a text file

Recommended Posts

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[i].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.

Share this post


Link to post
Share on other sites
To write an ArrayList to a file, I'd prefer to do the following:

// Make the array list
ArrayList arrayList= new ArrayList();
arrayList.Add("Hello");
arrayList.Add("World");

// Write it to a file
using(StreamWriter writer = new StreamWriter("playlist2.txt", false))
foreach(object s in arrayList)
writer.WriteLine(s.ToString());

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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!

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this