0

How can I store the contents of a char array into a text file in C# with .NET? I have tried

char[] characters = VarInput.ToCharArray();
System.IO.File.WriteAllText(@"C:\Users\leoga\Documents\Projects_Atom\Pad_Wood\WriteText2CharacterArray.txt", characters);

but it comes up with an error message saying

Argument 2: cannot convert from 'char[]' to 'string'
[C:\Users\leoga\Documents\Projects_Atom\Pad_Wood\converter.csproj]

I have also tried it with File.WriteAllLines() but it still doesn't work. I am using c# and .NET

4
  • What type is VarInput ? Commented Nov 30, 2019 at 21:53
  • @HenkHolterman VarInput is a text string Commented Nov 30, 2019 at 22:07
  • Then WriteAllText(path, VarInput); Commented Nov 30, 2019 at 22:46
  • Is the VarInput.ToCharArray() just for sample purposes and your code is really passed/provided a char[] with no way to associate it with the original string (or there was no string to begin with)? Or you do have a string and were thinking it can only be written to a file as individual chars? Commented Dec 1, 2019 at 0:44

3 Answers 3

4

What type is VarInput? If it's a string initially, just remove the ToCharArray() call and you can write it to a file directly with File.WriteAllText.

File.WriteAllText(path, VarInput);

Once you have a char array, you don't have to convert to a string in order to write to a file. You can also write bytes directly.

var bytes = System.Text.Encoding.UTF8.GetBytes(characters);
File.WriteAllBytes(path, bytes);
Sign up to request clarification or add additional context in comments.

Comments

1

Reason

  • Because OP converted the string to an array when there wasn't a need to, you can use it directly.

Other way

  • code
        public void Write(string path)
        {
            FileStream fs = new FileStream(path, FileMode.Create);
            using (fs)
            {
                StreamWriter sw = new StreamWriter(fs);
                using (sw)
                {
                    string VarInput = "11111111";
                    char[] characters = VarInput.ToCharArray();
                    sw.Write(characters);
                }
            }
        }

1 Comment

It has been updated. Thank you for pointing out.
-1

There should be a built in function to run joins on Arrays, converting to String.

Here's an example of doing this to export an array as a CSV:

String result = String.Join(",",arr)

If you're looking to just convert to a String without any delimiters, you can do something like this:

String result = String.Join("",arr)

1 Comment

Passing an empty string and a char[] to String.Join() would be the less-efficient alternative to just passing the char[] to the String(char[]) constructor (i.e. String result = new string(arr);).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.