向/从文件流写入和读取字节

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

我正在模拟文件系统。我很难在文件流中读取和写入字节。我的目标是将第一位切换为'1',表示它实际上确实包含数据。我已经设置了一个测试场景来表示我想要实现的目标。

问题是它似乎打开了位并将其写入_FileStream,但是,当我去读它时 - 我没有看到我的改变。

_Filestream = new FileStream(volumeName, FileMode.Open);
 _Filestream.Seek(0, SeekOrigin.Begin);

        //Test lines
        byte[] testAsBytes = new byte[_DirectoryUnitSize];
        testAsBytes[0] = 1;

        byte[] newDirectoryByteArray = new byte[_DirectoryUnitSize];

        _Filestream.Write(testAsBytes, 0, newDirectoryByteArray.Length);
        _Filestream.Flush();


         int bytesRead;
         byte[] buffer = new byte[64];
         char[] charBuffer = new char[64];


         List<byte> data = new List<byte>();
         while ((bytesRead = _Filestream.Read(buffer, 0, buffer.Length)) > 0) {
             if (!string.IsNullOrEmpty(Encoding.ASCII.GetString(buffer, 0, bytesRead))) {
                 data = Encoding.ASCII.GetBytes(charBuffer, 0, 1).ToList();

             }
        }
c# filestream
1个回答
0
投票

你有几个问题

1.为什么要创建另一个byte[] array - newDirectoryByteArray。似乎没必要,你可以简单地写

   _Filestream.Write(testAsBytes, 0, testAsBytes.Length);

2.当您写入文件时,光标随之移动,如果要使用相同的FileStream从文件中读取,则必须寻找所需的位置。例如,你必须打电话给_Filestream.Read(...)之前的意思。 Filestream.Seek(0, SeekOrigin.Begin);

来自MSDN

如果写操作成功,则流的当前位置按写入的字节数提前。如果发生异常,则流的当前位置不变。

  1. 线路data = Encoding.ASCII.GetBytes(charBuffer, 0, 1).ToList();将始终reutns 0因为没有数据写入charBuffer。您的数据位于buffer,它将在索引0处包含1,在所有其他指数处包含0

你可以看到它与Console.WriteLine(buffer[0]);将输出1和Console.WriteLine(data[0]);将输出0

© www.soinside.com 2019 - 2024. All rights reserved.