Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 逐字节反向文件读取_C#_Reverse - Fatal编程技术网

C# 逐字节反向文件读取

C# 逐字节反向文件读取,c#,reverse,C#,Reverse,这是我的密码 string FileName = @"File.txt"; if (File.Exists(FileName)) { FileStream fs = new FileStream(FileName, FileMode.Open, FileAccess.Read); BinaryReader br = new BinaryReader(fs); fo

这是我的密码

        string FileName = @"File.txt";    

        if (File.Exists(FileName))
        {
            FileStream fs = new FileStream(FileName, FileMode.Open, FileAccess.Read);

            BinaryReader br = new BinaryReader(fs);

            for (long i = fs.Length; i > 0; i--)
            {
                Console.Write(Convert.ToChar(br.Read()));
            }

        }
        else
        {
但是它仍然给了我同样的输出。。它从头到尾按正确的顺序读取文件。我要它从头到尾读

问题已解决 最终代码

string FileName = @"File.txt";

        if (File.Exists(FileName))
        {
            FileStream fs = new FileStream(FileName, FileMode.Open, FileAccess.Read);
            int length = (int)fs.Length;

            BinaryReader br = new BinaryReader(fs);

            byte[] myArray = br.ReadBytes((int)fs.Length);

            for (long i = myArray.Length - 1; i > 0; i--)
            {
                Console.Write(Convert.ToChar(myArray[i]));
            }
            Console.WriteLine();
        }
        else
        {
            Console.WriteLine("File Not Exists");
        }

您需要使用不同的
Read
方法(
Read(byte[]buffer,int index,int length)
)来指定要读取的数据的起始索引和长度

for(long i = fs.Length; i > 0; i--)
{
    byte[] buffer = new byte[1];
    br.Read(buffer, i, 1);
    Console.Write(Convert.ToChar(buffer[0]));
}
编辑:
我的方法不好,如果您想使用
读取(byte[],int,int)
方法,您应该首先读取整个文件,然后反转数组,正如@Crowcoder在他的解决方案中提到的那样。

只需读取流中的所有字节,将其保存到字节列表中,然后像这样反转:

List<byte> data = new List<byte>();
for (int i = 0; i < br.BaseStream.Length; ++i)
  data.Add(br.ReadByte());

data.Reverse();
列表数据=新列表();
对于(int i=0;i
使用ReadBytes(fs.Length)获取字节数组,然后使用数组上的循环。

根据文件大小,以下解决方案将消耗大量内存,因为它将在内存中保存文件内容的两个副本。但对于较小的文件(认为大小小于约10 MB)应该可以,并且易于理解:

// using System;
// using System.IO;

byte[] fileContents = File.ReadAllBytes(filePath);
byte[] reversedFileContents = Array.Reverse(fileContents);
… // process `reversedFileContents` instead of an input file stream
p.S.:如果您想处理较大的文件(大小超过MB的文件),则不应使用此解决方案,因为它可能很快导致
OutOfMemoryException
S。我建议您将大小合理(例如64 KB)的文件块读入内存(通过执行查找,从文件末尾开始,一直到文件开头),然后逐个处理