gpt4 book ai didi

javascript - 在 C# 中将 (Javascript)TypedArray 字符串转换为 byteArray 的最佳方法

转载 作者:行者123 更新时间:2023-11-28 03:29:04 25 4
gpt4 key购买 nike

我正在调用端点并返回字符串格式(JavaScript中的TypedArray),如下所示[12,44,36,132,22,19,99]并希望将该字符串转换回 byte[]

我正在使用

var byteData = Regex.Replace(fileData, @"\[*\]*", "").Split(',').Select(x => byte.Parse(x)).ToArray();

但只是想知道是否有更优雅的方法来做到这一点?谢谢大家

    protected void downloadFile(string fileKey)
{
var url = _apiFileDataUrl + fileKey;
_filename = fileKey.Split('/').LastOrDefault();
Log.Information($"Endpoint hit: {url}");

var requestData = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri(url)
};

requestData.Headers.Add("X-Auth", _x_auth);
requestData.Headers.Add("x-api-key", _x_api_key);
//requestData.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

var results = _client.SendAsync(requestData).Result;
if (results.StatusCode != HttpStatusCode.OK)
{
throw new Exception($"Campaign failure at fileKey {fileKey} \n\n {(int)results.StatusCode}: {results.ReasonPhrase}");
}

var fileData = results.Content.ReadAsStringAsync().Result;
if (fileData.Length > 0)
{
var byteData = Regex.Replace(fileData, @"\[*\]*", "").Split(',').Select(x => byte.Parse(x)).ToArray();
//var byteData = fileData.Replace("[", "").Replace("]", "").Split(',').Select(x => byte.Parse(x)).ToArray();
//var dt = DataTableHelper.CsvToDataTable(byteData, "\r\n",'|');
File.WriteAllBytes(DataFilePath + _filename, byteData);
}
}

最佳答案

或多或少,我会选择和你一样的道路。但是,对于这样一个简单的任务,我不会选择 Regex 路径。我的代码在必要时添加了注释。

    /// <summary>
/// Creates a byte array from the passed TypedArray in javascript.
/// </summary>
/// <param name="jsStringArray">TypedArray in javascript, like [12, 44, 36, 132, 22, 19, 99]</param>
/// <returns>Byte array created from passed string</returns>
private static byte[] StringArrayToByteArrayParser(string jsStringArray ) {
try{

// // No need to use heavy Regex
var sb = jsStringArray.Substring(1, jsStringArray.Length - 2);



// Splits using , then converts into byte array
return sb.ToString().Split(',').Select(byte.Parse).ToArray();
}
catch(ArgumentOutOfRangeException outOfRange) {
// Handle etc..
throw;
}
catch(Exception ex) {
// Here catch your exceptions throw or handle
throw;
}

}

关于javascript - 在 C# 中将 (Javascript)TypedArray 字符串转换为 byteArray 的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58332827/

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