gpt4 book ai didi

c# - 以相反的顺序一次一个字节地读取文件

转载 作者:行者123 更新时间:2023-11-30 12:30:30 29 4
gpt4 key购买 nike

您好,我正在尝试以相反的顺序一次读取一个文件。到目前为止,我只能设法从头到尾读取文件并将其写入另一个文件。

我需要能够从头到尾读取文件并将其打印到另一个文件。

这是我目前所拥有的:

        string fileName = Console.ReadLine();
using (FileStream file = new FileStream(fileName ,FileMode.Open , FileAccess.Read))
{

//file.Seek(endOfFile, SeekOrigin.End);

int bytes;
using (FileStream newFile = new FileStream("newsFile.txt" , FileMode.Create , FileAccess.Write))
{
while ((bytes = file.ReadByte()) >= 0)
{
Console.WriteLine(bytes.ToString());
newFile.WriteByte((byte)bytes);
}
}
}

我知道我必须在 fileStream 上使用 Seek 方法,这会让我到达文件的末尾。我已经在代码的注释部分这样做了,但我现在不知道如何读取文件在 while 循环中。

我怎样才能做到这一点?

最佳答案

    string fileName = Console.ReadLine();
using (FileStream file = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
byte[] output = new byte[file.Length]; // reversed file

// read the file backwards using SeekOrigin.Current
//
long offset;
file.Seek(0, SeekOrigin.End);
for (offset = 0; offset < fs.Length; offset++)
{
file.Seek(-1, SeekOrigin.Current);
output[offset] = (byte)file.ReadByte();
file.Seek(-1, SeekOrigin.Current);
}

// write entire reversed file array to new file
//
File.WriteAllBytes("newsFile.txt", output);
}

关于c# - 以相反的顺序一次一个字节地读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15931639/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com