从C#磁盘中读取短数组的最佳方法?

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

我必须在磁盘之间写入4GB short []数组,所以我找到了一个写入数组的函数,而我正在努力编写代码以从磁盘读取数组。我通常使用其他语言编写代码,因此,如果到目前为止我的尝试还有些可怜,请原谅:

using UnityEngine;
using System.Collections;
using System.IO;

public class RWShort : MonoBehaviour {

    public static void WriteShortArray(short[] values, string path)
    {
        using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
        {
            using (BinaryWriter bw = new BinaryWriter(fs))
            {
                foreach (short value in values)
                {
                    bw.Write(value);
                }
            }
        }
    } //Above is fine, here is where I am confused: 


    public static short[] ReadShortArray(string path) 
    {
        byte[]  thisByteArray= File.ReadAllBytes(fileName);
        short[] thisShortArray= new short[thisByteArray.length/2];      
                for (int i = 0; i < 10; i+=2)
                {
                    thisShortArray[i]= ? convert from byte array;
                }


        return thisShortArray;
    }   
}
c# filestream binarywriter
2个回答
1
投票

短裤是两个字节,因此您每次必须读两个字节。我还建议使用这样的yield return,这样您就不会尝试将所有内容一次性存储到内存中。虽然如果您需要一起使用所有短裤,那对您没有帮助。.我想这取决于您在做什么。

void Main()
{
    short[] values = new short[] {
        1, 999, 200, short.MinValue, short.MaxValue
    };

    WriteShortArray(values, @"C:\temp\shorts.txt");

    foreach (var shortInfile in ReadShortArray(@"C:\temp\shorts.txt"))
    {
        Console.WriteLine(shortInfile);
    }
}

public static void WriteShortArray(short[] values, string path)
{
    using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
    {
        using (BinaryWriter bw = new BinaryWriter(fs))
        {
            foreach (short value in values)
            {
                bw.Write(value);
            }
        }
    }
}

public static IEnumerable<short> ReadShortArray(string path)
{
    using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
    using (BinaryReader br = new BinaryReader(fs))
    {
        byte[] buffer = new byte[2];
        while (br.Read(buffer, 0, 2) > 0)
            yield return (short)(buffer[0]|(buffer[1]<<8)); 
    }
}

您也可以通过BinaryReader来定义它:

public static IEnumerable<short> ReadShortArray(string path)
{
    using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
    using (BinaryReader br = new BinaryReader(fs))
    {
        while (br.BaseStream.Position < br.BaseStream.Length)
            yield return br.ReadInt16();
    }
}

0
投票

内存映射文件是您的朋友,有一个MemoryMappedViewAccessor.ReadInt16函数可让您直接从OS磁盘缓存中读取类型为short的数据。

[MSDN上的Overview of using Memory-mapped files in .NET

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