Solved

Write ArrayList to Text File

Posted on 2011-03-23
13
3,183 Views
Last Modified: 2012-05-11
Hi All,

I'm trying to read in a text file to an ArrayList, alter a line and write the contents of the ArrayList to a text file with the following code:

private void writeConfig()
        {
            //Open file for reading
            StreamReader objReader = new StreamReader("c:\\FTP Software\\000000000000.cfg");

            //Store each line
            string sLine = "";
            ArrayList arrText = new ArrayList();

            //Write lines from file into reader object
            while (sLine != null)
            {
                sLine = objReader.ReadLine();
                if (sLine != null)
                    arrText.Add(sLine);
            }
            objReader.Close();

            //Write each line into array
            foreach (string sOutput in arrText)
                Console.WriteLine(sOutput);
            Console.ReadLine();

            //Write line with MAC address
            arrText[7] = "<APPLICATION APP_FILE_PATH=\"sip3.1.3C.ld\" CONFIG_FILES=\"" + strMac + "-phone.cfg, sip.cfg\" MISC_FILES=\"\" LOG_FILE_DIRECTORY=\"Log\" OVERRIDES_DIRECTORY=\"current\" CONTACTS_DIRECTORY=\"Contacts\" LICENSE_DIRECTORY=\"\">";

            using (StreamWriter outfile =
            new StreamWriter("c:\\FTP Software\\test.cfg"))
            {
                outfile.WriteLine(arrText.ToString());
            }

Open in new window


The issue is, the text file that's written has the contents of:

System.Collections.ArrayList

Open in new window


So I need a little guidance on how to output the actual contents of the ArrayList.

Thanks!
private void writeConfig()
        {
            //Open file for reading
            StreamReader objReader = new StreamReader("c:\\FTP Software\\000000000000.cfg");

            //Store each line
            string sLine = "";
            ArrayList arrText = new ArrayList();

            //Write lines from file into reader object
            while (sLine != null)
            {
                sLine = objReader.ReadLine();
                if (sLine != null)
                    arrText.Add(sLine);
            }
            objReader.Close();

            //Write each line into array
            foreach (string sOutput in arrText)
                Console.WriteLine(sOutput);
            Console.ReadLine();

            //Write line with MAC address
            arrText[7] = "<APPLICATION APP_FILE_PATH=\"sip3.1.3C.ld\" CONFIG_FILES=\"" + strMac + "-phone.cfg, sip.cfg\" MISC_FILES=\"\" LOG_FILE_DIRECTORY=\"Log\" OVERRIDES_DIRECTORY=\"current\" CONTACTS_DIRECTORY=\"Contacts\" LICENSE_DIRECTORY=\"\">";

            using (StreamWriter outfile =
            new StreamWriter("c:\\FTP Software\\test.cfg"))
            {
                outfile.WriteLine(arrText.ToString());
            }

Open in new window

0
Comment
Question by:ImaCircularSaw
  • 6
  • 4
  • 3
13 Comments
 
LVL 53

Expert Comment

by:Dhaest
Comment Utility
Try this:

using (StreamWriter outfile =
            new StreamWriter("c:\\FTP Software\\test.cfg"))
            {
                outfile.WriteLine(String.Join(Environment.NewLine , arrText)
            }
0
 
LVL 52

Expert Comment

by:Carl Tawn
Comment Utility
Or the simpler:
    System.IO.File.WriteAllLines("c:\\FTP Software\\test.cfg", list.ToArray());

Open in new window

0
 
LVL 10

Author Comment

by:ImaCircularSaw
Comment Utility
@Dhaest:

I added the following code:

using (StreamWriter outfile =
            new StreamWriter("c:\\FTP Software\\test.cfg"))
            {
                outfile.WriteLine(String.Join(Environment.NewLine, arrText));
            } 

Open in new window


and got the following errors:

The best overloaded method match for 'string.Join(string, string[])' has some invalid arguments

Open in new window

Argument '2': cannot convert from 'System.Collections.ArrayList' to 'string[]'

Open in new window



@carl

I replaced the entire using section with:

System.IO.File.WriteAllLines("c:\\FTP Software\\test.cfg", list.ToArray());

Open in new window


and got the error:

The name 'list' does not exist in the current context

Open in new window


Any advice guys?
 
0
 
LVL 53

Expert Comment

by:Dhaest
Comment Utility
My mistake. you still need to convert an arraylist to a string[]


outfile.WriteLine(String.Join(Environment.NewLine, arrText.ToArray(typeof(string)) ));

I'm not sure how you want to ouput it. you can choose the parameter

outfile.WriteLine(String.Join(",", arrText.ToArray(typeof(string)) ));
0
 
LVL 10

Author Comment

by:ImaCircularSaw
Comment Utility
@Dhaest:

Both of those lines threw the same errors:

The best overloaded method match for 'string.Join(string, string[])' has some invalid arguments
cannot convert from 'System.Array' to 'string[]'

Would you be able to put it together in the entire using section?  Sorry I'm not very familiar with this C# stuff not entirely sure of what I'm doing.

Thanks,
0
 
LVL 52

Expert Comment

by:Carl Tawn
Comment Utility
That was just an example, you need to replace list with the name of your ArrayList:
System.IO.File.WriteAllLines("c:\\FTP Software\\test.cfg", arrText.ToArray());

Open in new window

0
Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

 
LVL 10

Author Comment

by:ImaCircularSaw
Comment Utility
@Carl

I replaced the using section with your code so the entire method looks like

private void writeConfig()
        {
            //Open file for reading
            StreamReader objReader = new StreamReader("c:\\FTP Software\\000000000000.cfg");

            //Store each line
            string sLine = "";
            ArrayList arrText = new ArrayList();

            //Write lines from file into reader object
            while (sLine != null)
            {
                sLine = objReader.ReadLine();
                if (sLine != null)
                    arrText.Add(sLine);
            }
            objReader.Close();

            //Write each line into array
            foreach (string sOutput in arrText)
                Console.WriteLine(sOutput);
            Console.ReadLine();

            //Write line with MAC address
            arrText[7] = "<APPLICATION APP_FILE_PATH=\"sip3.1.3C.ld\" CONFIG_FILES=\"" + strMac + "-phone.cfg, sip.cfg\" MISC_FILES=\"\" LOG_FILE_DIRECTORY=\"Log\" OVERRIDES_DIRECTORY=\"current\" CONTACTS_DIRECTORY=\"Contacts\" LICENSE_DIRECTORY=\"\">";

            System.IO.File.WriteAllLines("c:\\FTP Software\\test.cfg", arrText.ToArray()); 

        }

Open in new window


However, I get the following errors still:

The best overloaded method match for 'System.IO.File.WriteAllLines(string, string[])' has some invalid arguments
Argument '2': cannot convert from 'object[]' to 'string[]'
0
 
LVL 52

Accepted Solution

by:
Carl Tawn earned 500 total points
Comment Utility
Ok, try it as:
System.IO.File.WriteAllLines("c:\\FTP Software\\test.cfg", arrText.ToArray(typeof(string))); 

Open in new window

On a side-note, if you are only storing strings then you would make life easier for yourself if you used the Generic List<> instead of teh ArrayList:
private void writeConfig()
        {
            //Open file for reading
            StreamReader objReader = new StreamReader("c:\\FTP Software\\000000000000.cfg");

            //Store each line
            string sLine = "";
            List<string> arrText = new List<string>();

            //Write lines from file into reader object
            while (sLine != null)
            {
                sLine = objReader.ReadLine();
                if (sLine != null)
                    arrText.Add(sLine);
            }
            objReader.Close();

            //Write each line into array
            foreach (string sOutput in arrText)
                Console.WriteLine(sOutput);
            Console.ReadLine();

            //Write line with MAC address
            arrText[7] = "<APPLICATION APP_FILE_PATH=\"sip3.1.3C.ld\" CONFIG_FILES=\"" + strMac + "-phone.cfg, sip.cfg\" MISC_FILES=\"\" LOG_FILE_DIRECTORY=\"Log\" OVERRIDES_DIRECTORY=\"current\" CONTACTS_DIRECTORY=\"Contacts\" LICENSE_DIRECTORY=\"\">";

            System.IO.File.WriteAllLines("c:\\FTP Software\\test.cfg", arrText.ToArray()); 

        }

Open in new window

0
 
LVL 53

Expert Comment

by:Dhaest
Comment Utility
Did a quick test: this should work

String.Join(",",(string []) arrText.ToArray(typeof(string)));
0
 
LVL 10

Author Comment

by:ImaCircularSaw
Comment Utility
@Carl,

That line still gives the same errors.  

I've replaced the method code with what you've suggested, dropped the line index by one and it works perfectly!  Thanks!

Could you spend a moment explaining why you suggested the use of generic list over arrayList?  I'll accept your previous post as the answer.
0
 
LVL 10

Author Closing Comment

by:ImaCircularSaw
Comment Utility
Even suggested a better technique.
0
 
LVL 52

Expert Comment

by:Carl Tawn
Comment Utility
Basically the List<> is strongly typed. When you create it you tell it what type of object it will be storing. Then, when you need to retrieve an item it will be returned as the correct "strong" type, so you don't need to cast it.

The ArrayList stores everything as object. Which means you can add objects of several different types to the same list. The problem with that is that you need to know in advance what type of object is in each slot of the arraylist in order to be able to use it. You also need to cast each item in the list to its correct type before you can use it.
0
 
LVL 10

Author Comment

by:ImaCircularSaw
Comment Utility
I see!

Thanks for the help, basically I'm trying to write a program that does all the config file changes for an IP phone system so I can eneter all the data in one form, hit submit, plug the phone in and job's done!

Cheers!
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Detect file exist or not 3 76
Handling arrays 14 33
How do I get the id from URL? 19 46
Why don't I see this table in EDMX file? 2 19
Article by: Ivo
Anonymous Types in C# by Ivo Stoykov Anonymous Types are useful when  we do not need to follow usual work-flow -- creating object of some type, assign some read-only values and then doing something with them. Instead we can encapsulate this read…
Article by: Najam
Having new technologies does not mean they will completely replace old components.  Recently I had to create WCF that will be called by VB6 component.  Here I will describe what steps one should follow while doing so, please feel free to post any qu…
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now