Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

Write ArrayList to Text File

Posted on 2011-03-23
13
3,316 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
ID: 35197136
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
ID: 35197161
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
ID: 35197316
@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
Networking for the Cloud Era

Join Microsoft and Riverbed for a discussion and demonstration of enhancements to SteelConnect:
-One-click orchestration and cloud connectivity in Azure environments
-Tight integration of SD-WAN and WAN optimization capabilities
-Scalability and resiliency equal to a data center

 
LVL 53

Expert Comment

by:Dhaest
ID: 35197339
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
ID: 35197369
@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
ID: 35197377
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
 
LVL 10

Author Comment

by:ImaCircularSaw
ID: 35197426
@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
ID: 35197438
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
ID: 35197448
Did a quick test: this should work

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

Author Comment

by:ImaCircularSaw
ID: 35197475
@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
ID: 35197478
Even suggested a better technique.
0
 
LVL 52

Expert Comment

by:Carl Tawn
ID: 35197489
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
ID: 35197565
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

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Two types of users will appreciate AOMEI Backupper Pro: 1 - Those with PCIe drives (and haven't found cloning software that works on them). 2 - Those who want a fast clone of their boot drive (no re-boots needed) and it can clone your drive wh…
In a recent question (https://www.experts-exchange.com/questions/29004105/Run-AutoHotkey-script-directly-from-Notepad.html) here at Experts Exchange, a member asked how to run an AutoHotkey script (.AHK) directly from Notepad++ (aka NPP). This video…

861 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