Jump to content
  • Advertisement
Sign in to follow this  
daniel_i_l

[.net] C# writing to a text file

This topic is 4280 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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.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
Advertisement
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!