CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 6 of 6
  1. #1
    Join Date
    Jun 2010
    Posts
    23

    [RESOLVED] Print out array contents into a text file

    How would i go about printing out the contents of an array into a text file.
    I know how to print single lines into a text file but not the contents of an entire array.

    Any help is greatly appreciated.

  2. #2
    Join Date
    Mar 2004
    Location
    Prague, Czech Republic, EU
    Posts
    1,701

    Re: Print out array contents into a text file

    By "print to text file" do you mean to save the text into the file? Try look here.
    • Make it run.
    • Make it right.
    • Make it fast.

    Don't hesitate to rate my post.

  3. #3
    Join Date
    Jun 2010
    Posts
    23

    Re: Print out array contents into a text file

    Yes, I would want to print each element of the array as a different line in a text file.

    i.e--- array lines = {"Each item","in this","array will","be printed out"," as a different line"}

    so in the text file this would print out to....each item would be a different line in it...

    could it be as simple as like a foreach loop for each item in the array?

  4. #4
    Join Date
    May 2007
    Location
    Denmark
    Posts
    623

    Re: Print out array contents into a text file

    The easiest way (I think) is to create a string and use the System.IO.File.WriteAllText method:

    Code:
    string contents = "";
    foreach(string line in lines)
       contents += line + Environment.Newline;
    File.WriteAllText(path, s, Encoding.Default);
    It's not a bug, it's a feature!

  5. #5
    Join Date
    Jun 2010
    Posts
    23

    Re: Print out array contents into a text file

    Thanks!

    Its actually a little easier this way i figured out:

    string[] lines = {"each","word","is","a","different","line"};
    File.WriteAllLines(@"c:\ttt.txt", lines, Encoding.Default);

    you dont even need a foreach loop just "File.WriteAllLines" and then the name of the array

  6. #6
    Join Date
    May 2007
    Location
    Denmark
    Posts
    623

    Re: [RESOLVED] Print out array contents into a text file

    You're right I'm just not used to having my data arranged in an array beforehand
    It's not a bug, it's a feature!

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured