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

Leo Gaunt
  • 711
  • 1
  • 8
  • 29
  • What type is `VarInput` ? – H H Nov 30 '19 at 21:53
  • @HenkHolterman VarInput is a text string – Leo Gaunt Nov 30 '19 at 22:07
  • Then `WriteAllText(path, VarInput);` – H H Nov 30 '19 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 `char`s? – Lance U. Matthews Dec 01 '19 at 00:44

3 Answers3

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);
Wieschie
  • 479
  • 1
  • 7
  • 15
0

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);
                }
            }
        }
ChaosFish
  • 62
  • 1
  • 8
-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)
sticky bit
  • 36,626
  • 12
  • 31
  • 42
mochsner
  • 307
  • 2
  • 10
  • 1
    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](https://learn.microsoft.com/dotnet/api/system.string.-ctor#System_String__ctor_System_Char___) (i.e. `String result = new string(arr);`). – Lance U. Matthews Dec 01 '19 at 00:27