Reputation: 6485
Is there a better way to implement conversion from a regular (large) string to IInputStream than this:
public static async Task<IInputStream> ToInputStream(this string input)
{
byte[] bytes = Encoding.UTF8.GetBytes(input);
var memoryStream = new InMemoryRandomAccessStream();
await memoryStream.WriteAsync(bytes.AsBuffer());
await memoryStream.FlushAsync();
memoryStream.Seek(0);
return memoryStream;
}
Upvotes: 3
Views: 1275
Reputation: 6485
As suggested by Chris Guzak here is another version, based on DataWriter.WriteString()
:
public async static Task<IInputStream> ToInputStreamAsync(this string input)
{
var ms = new InMemoryRandomAccessStream();
using(var dw = new DataWriter(ms))
{
dw.WriteString(input);
await dw.StoreAsync();
dw.DetachStream();
}
return ms;
}
Although not sure which one is better.
Upvotes: 2
Reputation: 131
DataWriter.WriteString() can be used for this. It writes the value in a specific format so check to make sure this is what you want.
Upvotes: 1
Reputation: 6485
OK, looks like there is a bit shorter version:
public static IInputStream ToInputStream(this string input)
{
byte[] bytes = Encoding.UTF8.GetBytes(input);
MemoryStream stream = new MemoryStream(bytes);
return stream.AsRandomAccessStream();
}
Upvotes: 3