我正在学习在 C# 中处理文件,我想在文件中编写Program.cs
另外一条语句。但我收到一个对我说的错误ThrowBytesOverFlow
。
我认为我必须将要写入的所有内容转换为char
数组,然后将其编码为bytes
.
我不知道我该如何解决这个问题!
FileStream afile = new FileStream(@"..\..\Program.cs", FileMode.Open, FileAccess.Read);
byte[] byteData = new byte[afile.Length];
char[] charData = new char[afile.Length];
afile.Seek(0, SeekOrigin.Begin);
afile.Read(byteData, 0, (int)afile.Length);
Decoder d = Encoding.UTF8.GetDecoder();
d.GetChars(byteData, 0, byteData.Length, charData, 0);
Console.WriteLine(charData);
afile.Close();
byte[] bdata;
char[] cdata;
FileStream stream = new FileStream(@"..\..\My file.txt", FileMode.Create);
cdata = "Testing Text!\n".ToCharArray();
bdata = new byte[cdata.Length];
Encoder e = Encoding.UTF8.GetEncoder();
e.GetBytes(cdata, 0,cdata.Length, bdata, 0, true);
stream.Seek(0, SeekOrigin.Begin);
stream.Write(bdata, 0, bdata.Length);
byte[] bydata = new byte[charData.Length];
e.GetBytes(charData, 0, charData.Length, bydata, 0, true);
stream.Write(bydata, 0, bydata.Length);
stream.Close();