2

我正在学习在 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();
4

1 回答 1

1

我不知道您是否故意在字节和编码级别工作以了解更多信息。如果是这样,那么这个答案将没有帮助。但是,以下代码应该可以满足您的目标:

string contents = File.ReadAllText(@"..\..\Program.cs");
using (StreamWriter file = new StreamWriter(@"..\..\My file.txt"))
{
    file.WriteLine("Testing Text!");
    file.Write(contents);
}

“using”语句,如果你不熟悉的话,它会在程序到达块的末尾时自动关闭我们正在写入的文件。相当于写:

StreamWriter file = new StreamWriter(@"..\..\My file.txt"))
file.WriteLine("Testing Text!");
file.Write(contents);
file.Close();

除了如果在 using 块内引发异常,则文件仍将关闭。

于 2013-01-31T14:33:09.633 回答