返回流的 C# 函数

本文关键字:函数 返回 | 更新日期: 2023-09-27 18:37:17

让我解释一下我要做什么:我为 Paint.NET 编写了一个文件类型插件,我希望该插件测试各种自定义编码方法并使用产生最小文件大小的方法保存文件。

这是我的实际代码(简化了很多只是为了演示我想做什么)。这奏效了,除了,好吧,请参阅评论:

private void encode1(Stream output)
{
    output.WriteByte(0xAA);
}
private void encode2(Stream output)
{
    output.WriteByte(0xAA);
    output.WriteByte(0xBB);
}
protected override void OnSave(Stream output)
{
    if (saveSmallest)
    {
        // I can't find a clean way to test for the smallest stream size
        // and then use the encoder that produced the smallest stream...
    }
    else if (selectedEncoder == 1)
    {
        encode1(output);
    }
    else if (selectedEncoder == 2)
    {
        encode2(output);
    }
}

所以这是我尝试过的(也简化了,但想法在这里),但它不起作用,在任何情况下都没有在文件中写入,我不知道为什么:

private Stream encode1()
{
    Stream output = new MemoryStream();
    output.WriteByte(0xAA);
    return output;
}
private Stream encode2()
{
    Stream output = new MemoryStream();
    output.WriteByte(0xAA);
    output.WriteByte(0xBB);
    return output;
}
private void copyStream(Stream input, Stream output)
{
    byte[] buffer = new byte[128];
    int read;
    while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
    {
        output.Write(buffer, 0, read);
    }
}
protected override void OnSave(Stream output)
{
    if (saveSmallest)
    {
        // get encoders's streams
        Stream[] outputs =
        {
            encode1(),
            encode2(),
            //other encoders here
        };
        // Find the smallest stream
        int smallest = 0;
        for (int i = 1; i < outputs.Length; i++)
        {
            if (outputs[i].Length < outputs[smallest].Length)
            {
                smallest = i;
            }
        }
        //Copy the smallest into the final output
        //output = outputs[smallest];
        copyStream(outputs[smallest], output);
    }
    else if (selectedEncoder == 1)
    {
        //output = encode1();
        copyStream(encode1(), output);
    }
    else if (selectedEncoder == 2)
    {
        //output = encode2();
        copyStream(encode2(), output);
    }
}

我也尝试使用字节数组而不是 Stream,但字节的问题在于我必须声明一个非常大的字节数组,因为我显然不知道编码需要多少字节。可能是数百万...

我是 C# 的初学者。请告诉我为什么它根本不起作用,以及我如何修复它,或者您是否知道如何改进。但是请不要编写复杂的代码,编译后需要多花费2kb,我希望代码小,简单和高效。我对较低级别的编程感觉更好...提前感谢!

返回流的 C# 函数

在复制流之前尝试Stream.Seek(0l, SeekOrigin.Begin);