MemoryStream
が入力されていることを知っている が与えられた場合String
、どうすれば元にString
戻すことができますか?
12 に答える
このサンプルでは、MemoryStream に対して文字列を読み書きする方法を示します。
Imports System.IO
Module Module1
Sub Main()
' We don't need to dispose any of the MemoryStream
' because it is a managed object. However, just for
' good practice, we'll close the MemoryStream.
Using ms As New MemoryStream
Dim sw As New StreamWriter(ms)
sw.WriteLine("Hello World")
' The string is currently stored in the
' StreamWriters buffer. Flushing the stream will
' force the string into the MemoryStream.
sw.Flush()
' If we dispose the StreamWriter now, it will close
' the BaseStream (which is our MemoryStream) which
' will prevent us from reading from our MemoryStream
'sw.Dispose()
' The StreamReader will read from the current
' position of the MemoryStream which is currently
' set at the end of the string we just wrote to it.
' We need to set the position to 0 in order to read
' from the beginning.
ms.Position = 0
Dim sr As New StreamReader(ms)
Dim myStr = sr.ReadToEnd()
Console.WriteLine(myStr)
' We can dispose our StreamWriter and StreamReader
' now, though this isn't necessary (they don't hold
' any resources open on their own).
sw.Dispose()
sr.Dispose()
End Using
Console.WriteLine("Press any key to continue.")
Console.ReadKey()
End Sub
End Module
使用することもできます
Encoding.ASCII.GetString(ms.ToArray());
これは効率が悪いとは思いませんが、断言できません。また、別のエンコーディングを選択することもできますが、StreamReader を使用する場合は、それをパラメーターとして指定する必要があります。
StreamReader を使用して MemoryStream を String に変換します。
<Extension()> _
Public Function ReadAll(ByVal memStream As MemoryStream) As String
' Reset the stream otherwise you will just get an empty string.
' Remember the position so we can restore it later.
Dim pos = memStream.Position
memStream.Position = 0
Dim reader As New StreamReader(memStream)
Dim str = reader.ReadToEnd()
' Reset the position so that subsequent writes are correct.
memStream.Position = pos
Return str
End Function
StreamReaderを使用すると、文字列を返すReadToEndメソッドを使用できます。
エンコーディングが関係する場合、以前のソリューションは機能しません。これが-「実生活」のようなものです-これを適切に行う方法の例...
using(var stream = new System.IO.MemoryStream())
{
var serializer = new DataContractJsonSerializer(typeof(IEnumerable<ExportData>), new[]{typeof(ExportData)}, Int32.MaxValue, true, null, false);
serializer.WriteObject(stream, model);
var jsonString = Encoding.Default.GetString((stream.ToArray()));
}
MemoryStream 型で素敵な拡張メソッドを作成してみませんか?
public static class MemoryStreamExtensions
{
static object streamLock = new object();
public static void WriteLine(this MemoryStream stream, string text, bool flush)
{
byte[] bytes = Encoding.UTF8.GetBytes(text + Environment.NewLine);
lock (streamLock)
{
stream.Write(bytes, 0, bytes.Length);
if (flush)
{
stream.Flush();
}
}
}
public static void WriteLine(this MemoryStream stream, string formatString, bool flush, params string[] strings)
{
byte[] bytes = Encoding.UTF8.GetBytes(String.Format(formatString, strings) + Environment.NewLine);
lock (streamLock)
{
stream.Write(bytes, 0, bytes.Length);
if (flush)
{
stream.Flush();
}
}
}
public static void WriteToConsole(this MemoryStream stream)
{
lock (streamLock)
{
long temporary = stream.Position;
stream.Position = 0;
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8, false, 0x1000, true))
{
string text = reader.ReadToEnd();
if (!String.IsNullOrEmpty(text))
{
Console.WriteLine(text);
}
}
stream.Position = temporary;
}
}
}
もちろん、これらのメソッドを標準のメソッドと組み合わせて使用する場合は注意が必要です。:) ...同時実行のために、その便利な streamLock を使用する必要があります。
ブライアンの回答を少し修正したバージョンでは、読み取り開始のオプションの管理が可能です。これが最も簡単な方法のようです。おそらく最も効率的ではありませんが、理解しやすく使いやすいです。
Public Function ReadAll(ByVal memStream As MemoryStream, Optional ByVal startPos As Integer = 0) As String
' reset the stream or we'll get an empty string returned
' remember the position so we can restore it later
Dim Pos = memStream.Position
memStream.Position = startPos
Dim reader As New StreamReader(memStream)
Dim str = reader.ReadToEnd()
' reset the position so that subsequent writes are correct
memStream.Position = Pos
Return str
End Function
Stream to Write を必要とするクラスと統合する必要があります。
XmlSchema schema;
// ... Use "schema" ...
var ret = "";
using (var ms = new MemoryStream())
{
schema.Write(ms);
ret = Encoding.ASCII.GetString(ms.ToArray());
}
//here you can use "ret"
// 6 Lines of code
複数回使用するためにコード行を減らすのに役立つ単純なクラスを作成します。
public static class MemoryStreamStringWrapper
{
public static string Write(Action<MemoryStream> action)
{
var ret = "";
using (var ms = new MemoryStream())
{
action(ms);
ret = Encoding.ASCII.GetString(ms.ToArray());
}
return ret;
}
}
その後、サンプルを 1 行のコードに置き換えることができます
var ret = MemoryStreamStringWrapper.Write(schema.Write);
メソッド Convert.ToBase64String のみを使用
Convert.ToBase64String(inputStream.ToArray());