2

私はC#が初めてで、非常に基本的な問題に悩まされています。

いくつかのデータ (「hello」など) を含む 1 つのテキスト ファイルを読み込んでいます。このデータを以下のコードのように読み込んでいます。

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;

「こんにちは」を「strFinalFileContent」の値にする必要があります。「104 101 108 108 111」は ASCII 文字の 10 進数値を意味します。出力として「hello」を取得する方法を教えてください。些細な質問かもしれませんが初心者なので教えてください。

4

3 に答える 3

6

オブジェクトを使用Encodingして、バイナリ データをテキストに変換するために使用するエンコーディングを指定する必要があります。入力ファイルが実際に何であるか、または事前にエンコーディングを知っているかどうかは、あなたの投稿からは明らかではありませんが、知っていればはるかに簡単です。

StreamReader指定されたエンコーディングを使用して を作成し、ストリームをラップして、そこからテキストを読み取ることをお勧めします。そうしないと、文字がバイナリ読み取りに分割されている場合、「文字の半分」を読み取るのに興味深い問題が発生する可能性があります。

また、この行は危険であることに注意してください。

myStream.Read(Input, 0, fileLen);

この 1 回の呼び出しですべてのデータが読み取られると想定しています。一般に、これはストリームには当てはまりません。(または)の戻り値を使用して、実際にどれだけ読んだかを確認する必要があります。ReadStream.ReadTextReader.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();
}
于 2013-09-18T13:46:50.220 に答える
0

すべてのテキストを文字列変数に読み込みます

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

特定のエンコーディングが必要な場合は、 new StreamReader にオーバーロードを使用することを忘れないでください。 StreamReader ドキュメント

次に、各文字の間にスペースを追加します(その要求は私には奇妙ですが、本当にしたい場合は...)

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

これは、各文字を取り、それを配列に分割し、linq を使用してそれぞれに追加のスペースを追加してから、結果を結合文字列に連結します。

これで問題が解決することを願っています!

于 2013-09-18T13:44:54.343 に答える