Solved

Write ArrayList to Text File

Posted on 2011-03-23
13
3,266 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
Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

 
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

NAS Cloud Backup Strategies

This article explains backup scenarios when using network storage. We review the so-called “3-2-1 strategy” and summarize the methods you can use to send NAS data to the cloud

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Wav problem 4 27
C# bracket error 3 31
Need to start a web service from Visual Studio 2015 Pro 2 24
transaction in asp.net, sql server 6 33
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
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…
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…

777 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