gpt4 book ai didi

c# - 读/写字符串二进制数据 - BinaryReader

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

我写了下面的方法来使用二进制模式将文件归档到一个文件中:

        // Compile archive
public void CompileArchive(string FilePath, ListView FilesList, Label Status, ProgressBar Progress)
{
FileTemplate TempFile = new FileTemplate();
if (FilesList.Items.Count > 0)
{
BinaryWriter Writer = new BinaryWriter(File.Open(FilePath, FileMode.Create), System.Text.Encoding.ASCII);
Progress.Maximum = FilesList.Items.Count - 1;
Writer.Write((long)FilesList.Items.Count);
for (int i = 0; i <= FilesList.Items.Count - 1; i++)
{
TempFile.Name = FilesList.Items[i].SubItems[1].Text;
TempFile.Path = "%ARCHIVE%";
TempFile.Data = this.ReadFileData(FilesList.Items[i].SubItems[2].Text + "\\" + TempFile.Name);
Writer.Write(TempFile.Name);
Writer.Write(TempFile.Path);
Writer.Write(TempFile.Data);
Status.Text = "Status: Writing '" + TempFile.Name + "'";
Progress.Value = i;
}
Writer.Close();
Status.Text = "Status: None";
Progress.Value = 0;
}
}

我使用上面方法方法中的 ReadFileData 读取文件数据,它返回一串数据。 (StreamReader) 接下来我提取我的文件。一切都做得很好,但是将存储在提取方法中的数据没有给我正确的数据,因此提取的文件没有正确的数据来显示其原始功能。

提取方法:

    // Extract archive
public void ExtractArchive(string ArchivePath, string ExtractPath, ListView FilesList, Label Status, ProgressBar Progress)
{
FileTemplate TempFile = new FileTemplate();
BinaryReader Reader = new BinaryReader(File.Open(ArchivePath, FileMode.Open), System.Text.Encoding.ASCII);
long Count = Reader.ReadInt64();
if (Count > 0)
{
Progress.Maximum = (int)Count - 1;
FilesList.Items.Clear();
for (int i = 0; i <= Count - 1; i++)
{
TempFile.Name = Reader.ReadString();
TempFile.Path = Reader.ReadString();
TempFile.Data = Reader.ReadString();
Status.Text = "Status: Reading '" + TempFile.Name + "'";
Progress.Value = i;
if (!Directory.Exists(ExtractPath))
{
Directory.CreateDirectory(ExtractPath);
}
BinaryWriter Writer = new BinaryWriter(File.Open(ExtractPath + "\\" + TempFile.Name, FileMode.Create), System.Text.Encoding.ASCII);
Writer.Write(TempFile.Data);
Writer.Close();
string[] ItemArr = new string[] { i.ToString(), TempFile.Name, TempFile.Path };
ListViewItem ListItem = new ListViewItem(ItemArr);
FilesList.Items.Add(ListItem);
}
Reader.Close();
Status.Text = "Status: None";
Progress.Value = 0;
}
}

结构:

struct FileTemplate
{
public string Name, Path, Data;
}

谢谢。

最佳答案

考虑使用字节数组来写入和保护数据。

字节数组(写入)

Byte[] bytes = File.ReadAllBytes(..);
// Write it into your stream
myStream.Write(bytes.Count);
myStream.Write(bytes, 0, bytes.Count);

字节数组(读取)

Int32 byteCount = myStream.ReadInt32();
Byte[] bytes = new Byte[byteCount];
myStream.Read(bytes, 0, byteCount);

关于c# - 读/写字符串二进制数据 - BinaryReader,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8196350/

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