Whats the eisest way to turn a char array into a string

im trying out the ReadBlock function to get characters out of an array then i'd like them to be turned into a string. Is there anything eiser than this ( using a for loop to put the characters in the string one by one) -

using System;

using System.IO;

using System.Data;

namespace myProgram

{

class Program

{

static void Main(string[] args)

{

string mystring = "";

char[] mychar = new char[10];

Stream settings = new FileStream("information.ini", FileMode.Open, FileAccess.Read);

StreamReader currentline = new StreamReader(settings);

currentline.ReadBlock(mychar, 0, 9);

for (int i = 0; i < mychar.Length; i++)

{

mystring += mycharIdea;

}

Console.WriteLine(mystring);

}

}

}



Answer this question

Whats the eisest way to turn a char array into a string

  • syedasad

    Thanks! That works. I knew it had to be somthing simple like that...
  • Vorn

    Hi there,

    One of the constructors for string actually takes as a paramater an array of characters. Perhaps an example would be good at this stage:

    char[] mychar = new char[10];

    mychar[0] = 'N';
    mychar[1] = 'a';
    mychar[2] = 't';
    mychar[3] = 'e';
    mychar[4] = 'V';
    mychar[5] = '_';
    mychar[ 6] = 'T';
    mychar[7] = 'e';
    mychar[ 8] = 's';
    mychar[9] = 't';

    string x = new string(mychar);
    MessageBox.Show(x);

    Note that I have typed [ 6] and [ 8] in the above code. You'll need to remove the spaces in front of the "6" and the "8" so that your IDE doesn't complain....I had to put spaces in because otherwise the post would look like it had emoticons there. Sorry about this inconvenience.

    At the end, the message box will display the string "NateV_Test", which is an amalgamation of all the elements in the character array mychar.

    Hope this example helps you a bit, but sorry if it doesn't


  • Whats the eisest way to turn a char array into a string