簡體   English   中英

在c#中將byte []附加到字符串中

[英]To append a byte[] to a string in c#

我的JavaScript代碼將數據的Blob發送到C#中的處理程序。 我的Javascript代碼工作正常,並且我已經嘗試從client(javascript)接收數據並將它們傳遞給C#處理程序並將其保存在本地文件夾中。

現在,我不想將數據保存在文件夾中,而是將其保存在string
我的處理程序每​​次都以byte[]獲取我的信息。

我的Javascript:

xhr = new XMLHttpRequest();
// this is not the complete code 
// I slice my file and push them in var blobs = [];
blobs.push(file.slice(start, end));
while (blob = blobs.shift()) {

    xhr.send(blob);
    count++;
}

我的C#處理程序:在這里, bool ok永遠不會設置為true 從javascript發送文件時,如何逐塊獲取所有文件; 並且,而不是保存在文件夾中,而是將其保存在字符串中?

public void ProcessRequest(HttpContext context)
{
    try
    {
        byte[] buffer = new byte[context.Request.ContentLength];
        context.Request.InputStream.Read(buffer, 0, context.Request.ContentLength);
        string fileSize = context.Request.Headers.Get("X_FILE_SIZE");

        bool ok = false;
        System.Text.StringBuilder myData = new System.Text.StringBuilder();
        myData.Append(buffer);
        if(myData.Length == int.Parse(fileSize)){ ok=true;  }

    }
    catch (Exception)
    {

        throw;
    }
}

沒有使用字節數組的StringBuilder.Append重載,因此它將調用StringBuilder.Append(object)方法。 這將在字節數組上調用ToString以獲取字符串值,這將導致字符串"System.Byte[]"

要獲取字節數組作為字符串,您需要知道字節代表什么。 例如,如果字節是編碼為UTF-8的文本,則可以使用Encoding.UTF8類對其進行解碼:

myData.Append(Encoding.UTF8.GetString(buffer));

請注意,像UTF-8這樣的多字節編碼可能會將一個字符表示為多個字節,因此字符串長度可能與字節數組長度不同。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM