首页 > 解决方案 > 最小化 Base64

问题描述

所以,我在 C# 中有一个代码,可以将 Image 转换为 base64,反之亦然。现在,我想将生成的 base64 发送到 python。

这是我现有的代码。

            var startProcess = new ProcessStartInfo
            {
                FileName = pythonInterpreter,
                Arguments = string.Format($"\"{pythonPathAndCode}\" {b64stringCSharp}"),
                UseShellExecute = false,
                RedirectStandardOutput = true,
                RedirectStandardInput = true,
                RedirectStandardError = true,
                CreateNoWindow = true,
            };

            using (Process process = Process.Start(startProcess))
            {
                error = process.StandardError.ReadToEnd();
                testResult = process.StandardOutput.ReadToEnd();
                lblTestOutput.Text = testResult;
                lblError.Text = error;
            }

当我尝试向 python 发送一个小的字符串值时,这段代码工作得很好。但是在发送base64值的时候,出现了异常错误。

System.ComponentModel.Win32Exception: '文件名或扩展名太长'

请注意,当我仅发送 32,000 个字符串或更少但 base64 正好包含 98,260 时,代码工作得非常好。

有没有办法最小化这个base64?

这是我的python代码:

import sys

inputFromC = sys.stdin
print("Python Recevied: ", inputFromC)

标签: pythonc#base64

解决方案


Windows 中命令 + 参数的最大长度为 32767 个字符(链接)。这与您所看到的一致。

我建议改为通过进程的标准输入发送图像。就像是:

var startProcess = new ProcessStartInfo
{
    FileName = pythonInterpreter,
    Arguments = string.Format($"\"{pythonPathAndCode}\""),
    UseShellExecute = false,
    RedirectStandardOutput = true,
    RedirectStandardInput = true,
    RedirectStandardError = true,
    CreateNoWindow = true,
};

using (Process process = Process.Start(startProcess))
{
    process.StandardInput.Write(b64stringCSharp);
    process.StandardInput.Close();

    error = process.StandardError.ReadToEnd();
    testResult = process.StandardOutput.ReadToEnd();
    lblTestOutput.Text = testResult;
    lblError.Text = error;
}

显然,修改您的 Python 脚本以从标准输入读取,而不是从命令行参数读取。


推荐阅读