您如何将char []数组存储到c#(使用System.IO).NET中的文本文件中? [重复]

问题描述 投票:0回答:3

如何使用.NET将char数组的内容存储到C#中的文本文件中?我已经尝试过

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

但出现错误消息,提示

参数2:无法从'char []'转换为'string'[C:\ Users \ leoga \ Documents \ Projects_Atom \ Pad_Wood \ converter.csproj]

我也用File.WriteAllLines()尝试过,但仍然不起作用。我正在使用c#和.NET

c# arrays .net visual-studio-code system.io.file
3个回答
0
投票

应该有一个内置函数来在数组上运行联接,并转换为字符串。

这是将数组导出为CSV的示例:

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

如果您只想转换为不带任何分隔符的字符串,则可以执行以下操作:

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

2
投票

VarInput是什么类型?如果最初是字符串,则删除ToCharArray()调用,然后可以使用File.WriteAllText直接将其写入文件。

File.WriteAllText(path, VarInput);

一旦有了char数组,就不必转换为字符串即可写入文件。您也可以直接写入字节。

var bytes = System.Text.Encoding.UTF8.GetBytes(characters);
File.WriteAllBytes(path, bytes);

0
投票

原因

  • 因为OP不需要时将字符串转换为数组,所以可以直接使用它。

其他方式

  • 代码
        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);
                }
            }
        }
© www.soinside.com 2019 - 2024. All rights reserved.