簡體   English   中英

字節數組到C#中的字符串

[英]Byte Array to String in C#

作為C#的新手,我遇到了一個非常基本的問題。

我正在讀取一個文本文件,其中包含一些數據(例如“ hello”),我正在讀取此數據,如下面提到的代碼。

System.IO.Stream myStream;
Int32 fileLen;
StringBuilder displayString = new StringBuilder();

// Get the length of the file.
fileLen = FileUploadId.PostedFile.ContentLength;

// Display the length of the file in a label.
string strLengthOfFileInByte = "The length of the file is " +
fileLen.ToString() + " bytes.";

// Create a byte array to hold the contents of the file.
Byte[] Input = new Byte[fileLen];
// Initialize the stream to read the uploaded file.
myStream = FileUploadId.FileContent;

// Read the file into the byte array.
//myStream.Read(Input, 0, fileLen);

myStream.Read(Input, 0, fileLen);

// Copy the byte array to a string.
for (int loop1 = 0; loop1 < fileLen; loop1++)
{
    displayString.Append(Input[loop1].ToString());
}

// Display the contents of the file in a 
string strFinalFileContent = displayString.ToString();

return strFinalFileContent;

我希望“ hello”應為“ strFinalFileContent”的值。 我得到“ 104 101 108 108 111”表示ASCII字符的十進制值。 請幫助我如何獲取“ hello”作為輸出。 這可能是我的一個小問題,但我是初學者,所以請幫助我。

您應該使用Encoding對象來指定要用於將二進制數據轉換為文本的編碼。 從您的帖子中尚不清楚輸入文件實際上是什么,或者您是否會事先知道編碼-但這簡單得多。

我建議您使用給定的編碼創建StreamReader ,包裝流-並從中讀取文本。 否則,如果將字符拆分為二進制讀操作,則在讀取“半個字符”時會遇到有趣的困難。

另請注意,此行很危險:

myStream.Read(Input, 0, fileLen);

假設此一次Read調用將讀取所有數據。 通常,對於流而言並非如此。 您應該始終使用Stream.Read (或TextReader.Read )的返回值來查看實際讀取了多少。

實際上,使用StreamReader將使所有這些變得更加簡單。 您的整個代碼可以替換為:

// Replace Encoding.UTF8 with whichever encoding you're interested in. If you
// don't specify an encoding at all, it will default to UTF-8.
using (var reader = new StreamReader(FileUploadId.FileContent, Encoding.UTF8))
{
    return reader.ReadToEnd();
}

將所有文本讀入字符串變量

string fileContent;
using(StreamReader sr = new StreamReader("Your file path here")){
    sr.ReadToEnd();
}

如果您需要特定的編碼,請不要忘記對新的StreamReader使用重載。 StreamReader文檔

然后在每個字符之間添加一個空格(該請求對我來說很奇怪,但是如果您確實想要...)

string withSpaces = string.Concat(fileContent.ToCharArray().Select(n=>n + " ").ToArray());

這將占用每個字符,將其拆分為一個數組,使用linq進行投影,以為每個字符添加一個額外的空間,然后將結果連接到一個連接的字符串中。

希望這能解決您的問題!

string displayString = System.Text.Encoding.UTF8.GetString(Input);

暫無
暫無

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

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