本文整理汇总了C#中Stream.AsInputStream方法的典型用法代码示例。如果您正苦于以下问题:C# Stream.AsInputStream方法的具体用法?C# Stream.AsInputStream怎么用?C# Stream.AsInputStream使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Stream
的用法示例。
在下文中一共展示了Stream.AsInputStream方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: UploadImageAsync
public static async Task<string> UploadImageAsync(Stream imageStream)
{
CloudStorageAccount account = new CloudStorageAccount(
useHttps: true,
storageCredentials: new Microsoft.WindowsAzure.Storage.Auth.StorageCredentials(
accountName: Constants.StorageAccountName,
keyValue: Constants.StorageAccessKey)
);
try
{
var blobClient = account.CreateCloudBlobClient();
var container = blobClient.GetContainerReference("visitors");
var blob = container.GetBlockBlobReference(Guid.NewGuid().ToString() + ".jpg");
using (var stream = imageStream.AsInputStream())
{
await blob.UploadFromStreamAsync(stream);
}
return blob.Uri.ToString();
}
catch (Exception ex)
{
return null;
}
}
示例2: getBytes
public async static Task<byte[]> getBytes(Stream stream)
{
IInputStream inputStream = stream.AsInputStream();
DataReader dataReader = new DataReader(inputStream);
await dataReader.LoadAsync((uint)stream.Length);
byte[] buffer = new byte[(int)stream.Length];
dataReader.ReadBytes(buffer);
return buffer;
}
示例3: WriteFileAsync
/// <summary>
/// Write the contents of stream to filename in the cache location. If a null stream is provided, the file is created with no contents.
/// </summary>
/// <param name="stream">Content to be written to file</param>
/// <param name="filename">Name of the file to be written in cache location</param>
private static async Task WriteFileAsync(Stream stream, string filename)
{
// Prepare output file stream
StorageFolder parent = GetCacheFolder();
StorageFile file = null;
try
{
file = await parent.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
}
catch (Exception)
{
}
if (file != null && stream != null)
{
// Prepare input image stream
IInputStream inStream = stream.AsInputStream();
DataReader reader = new DataReader(inStream);
IRandomAccessStream fileStream = null;
try
{
fileStream = await file.OpenAsync(FileAccessMode.ReadWrite);
// Buffered write to file
await reader.LoadAsync(1024);
while (reader.UnconsumedBufferLength > 0)
{
await fileStream.WriteAsync(reader.ReadBuffer(reader.UnconsumedBufferLength));
await reader.LoadAsync(1024);
}
}
catch (Exception)
{
}
finally
{
if (fileStream != null)
{
fileStream.FlushAsync();
}
}
inStream.Dispose();
}
}
示例4: init
protected override async void init(Stream stream, bool flip, Loader.LoadedCallbackMethod loadedCallback)
{
try
{
using (var memoryStream = new InMemoryRandomAccessStream())
{
await RandomAccessStream.CopyAsync(stream.AsInputStream(), memoryStream);
var decoder = await BitmapDecoder.CreateAsync(memoryStream);
var frame = await decoder.GetFrameAsync(0);
var transform = new BitmapTransform();
transform.InterpolationMode = BitmapInterpolationMode.NearestNeighbor;
transform.Rotation = BitmapRotation.None;
var dataProvider = await decoder.GetPixelDataAsync(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Straight, transform, ExifOrientationMode.IgnoreExifOrientation, ColorManagementMode.ColorManageToSRgb);
var data = dataProvider.DetachPixelData();
int width = (int)decoder.PixelWidth;
int height = (int)decoder.PixelHeight;
Mipmaps = new Mipmap[1];
Size = new Size2(width, height);
Mipmaps[0] = new Mipmap(data, width, height, 1, 4);
if (flip) Mipmaps[0].FlipVertical();
}
}
catch (Exception e)
{
FailedToLoad = true;
Loader.AddLoadableException(e);
if (loadedCallback != null) loadedCallback(this, false);
return;
}
Loaded = true;
if (loadedCallback != null) loadedCallback(this, true);
}
示例5: WriteBlockAsync
#pragma warning disable 4014
/// <summary>
/// Starts an asynchronous PutBlock operation as soon as the parallel
/// operation semaphore becomes available.
/// </summary>
/// <param name="blockData">Data to be uploaded</param>
/// <param name="blockId">Block ID</param>
/// <returns>A task that represents the asynchronous write operation.</returns>
/// <remarks>Warning CS4014 is disabled here, since we intentionally do not
/// await PutBlockAsync call.</remarks>
private async Task WriteBlockAsync(Stream blockData, string blockId, string blockMD5)
{
Interlocked.Increment(ref this.pendingWrites);
this.noPendingWritesEvent.Reset();
await this.parallelOperationSemaphore.WaitAsync();
// Without await have found last block doesn't get uploaded properly and noPendingWritesEvent will always equal 1.
// Then the putblocklist will never happen, therefore no blob. Bug #211
await this.blockBlob.PutBlockAsync(blockId, blockData.AsInputStream(), blockMD5, this.accessCondition, this.options, this.operationContext).AsTask().ContinueWith(task =>
{
if (task.Exception != null)
{
this.lastException = task.Exception;
}
if (Interlocked.Decrement(ref this.pendingWrites) == 0)
{
this.noPendingWritesEvent.Set();
}
this.parallelOperationSemaphore.Release();
});
}
示例6: Upload
public static async void Upload(string uri, Stream data, string paramName, string uploadContentType,Action<VKHttpResult> resultCallback, Action<double> progressCallback = null, string fileName = null)
{
#if SILVERLIGHT
var rState = new RequestState();
rState.resultCallback = resultCallback;
#endif
try
{
#if SILVERLIGHT
var request = (HttpWebRequest)WebRequest.Create(uri);
request.AllowWriteStreamBuffering = false;
rState.request = request;
request.Method = "POST";
string formDataBoundary = String.Format("----------{0:N}", Guid.NewGuid());
string contentType = "multipart/form-data; boundary=" + formDataBoundary;
request.ContentType = contentType;
request.CookieContainer = new CookieContainer();
string header = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\";\r\nContent-Type: {3}\r\n\r\n",
formDataBoundary,
paramName,
fileName ?? "myDataFile",
uploadContentType);
string footer = "\r\n--" + formDataBoundary + "--\r\n";
request.ContentLength = Encoding.UTF8.GetByteCount(header) + data.Length + Encoding.UTF8.GetByteCount(footer);
request.BeginGetRequestStream(ar =>
{
try
{
var requestStream = request.EndGetRequestStream(ar);
requestStream.Write(Encoding.UTF8.GetBytes(header), 0, Encoding.UTF8.GetByteCount(header));
StreamUtils.CopyStream(data, requestStream, progressCallback);
requestStream.Write(Encoding.UTF8.GetBytes(footer), 0, Encoding.UTF8.GetByteCount(footer));
requestStream.Close();
request.BeginGetResponse(new AsyncCallback(ResponseCallback), rState);
}
catch (Exception ex)
{
Logger.Error("VKHttpRequestHelper.Upload failed to write data to request stream.", ex);
SafeClose(rState);
SafeInvokeCallback(rState.resultCallback, false, null);
}
}, null);
#else
var httpClient = new Windows.Web.Http.HttpClient();
HttpMultipartFormDataContent content = new HttpMultipartFormDataContent();
content.Add(new HttpStreamContent(data.AsInputStream()), paramName, fileName ?? "myDataFile");
content.Headers.Add("Content-Type", uploadContentType);
var postAsyncOp = httpClient.PostAsync(new Uri(uri, UriKind.Absolute),
content);
postAsyncOp.Progress = (r, progress) =>
{
if (progressCallback != null && progress.TotalBytesToSend.HasValue && progress.TotalBytesToSend > 0)
{
progressCallback(((double)progress.BytesSent * 100) / progress.TotalBytesToSend.Value);
}
};
var result = await postAsyncOp;
var resultStr = await result.Content.ReadAsStringAsync();
SafeInvokeCallback(resultCallback, result.IsSuccessStatusCode, resultStr);
#endif
}
catch (Exception exc)
{
Logger.Error("VKHttpRequestHelper.Upload failed.", exc);
#if SILVERLIGHT
SafeClose(rState);
SafeInvokeCallback(rState.resultCallback, false, null);
#else
SafeInvokeCallback(resultCallback, false, null);
#endif
}
}
示例7: LoadStrokesFromStream
private async void LoadStrokesFromStream(Stream stream)
{
await inkManager.LoadAsync(stream.AsInputStream());
strokeList.Clear();
strokeList.AddRange(inkManager.GetStrokes());
needsInkSurfaceValidation = true;
}
示例8: MD5
/// <summary>
/// Return the MD5 hash of the provided memory stream as a string. Stream position will be equal to the length of stream on
/// return, this ensures the MD5 is consistent.
/// </summary>
/// <param name="streamToMD5">The bytes which will be checksummed</param>
/// <returns>The MD5 checksum as a string</returns>
public static string MD5(Stream streamToMD5)
{
if (streamToMD5 == null) throw new ArgumentNullException("streamToMD5", "Provided Stream cannot be null.");
string resultStr;
#if NETFX_CORE
var alg = Windows.Security.Cryptography.Core.HashAlgorithmProvider.OpenAlgorithm(Windows.Security.Cryptography.Core.HashAlgorithmNames.Md5);
var buffer = (new Windows.Storage.Streams.DataReader(streamToMD5.AsInputStream())).ReadBuffer((uint)streamToMD5.Length);
var hashedData = alg.HashData(buffer);
resultStr = Windows.Security.Cryptography.CryptographicBuffer.EncodeToHexString(hashedData).Replace("-", "");
#else
using (System.Security.Cryptography.HashAlgorithm md5 =
#if WINDOWS_PHONE
new Tools.MD5Managed())
#else
System.Security.Cryptography.MD5.Create())
#endif
{
//If we don't ensure the position is consistent the MD5 changes
streamToMD5.Seek(0, SeekOrigin.Begin);
resultStr = BitConverter.ToString(md5.ComputeHash(streamToMD5)).Replace("-", "");
}
#endif
return resultStr;
}
示例9: VoiceRequestAsync
public async Task<AIResponse> VoiceRequestAsync(Stream voiceStream, RequestExtras requestExtras = null)
{
var request = new AIRequest
{
Language = config.Language.code,
Timezone = TimeZoneInfo.Local.StandardName,
SessionId = sessionId
};
if (requestExtras != null)
{
if (requestExtras.HasContexts)
{
request.Contexts = requestExtras.Contexts;
}
if (requestExtras.HasEntities)
{
request.Entities = requestExtras.Entities;
}
}
try
{
var content = new HttpMultipartFormDataContent();
var jsonRequest = JsonConvert.SerializeObject(request, Formatting.None, jsonSettings);
if (config.DebugLog)
{
Debug.WriteLine($"Request: {jsonRequest}");
}
content.Add(new HttpStringContent(jsonRequest, UnicodeEncoding.Utf8, "application/json"), "request");
content.Add(new HttpStreamContent(voiceStream.AsInputStream()), "voiceData", "voice.wav");
var response = await httpClient.PostAsync(new Uri(config.RequestUrl), content);
return await ProcessResponse(response);
}
catch (Exception e)
{
throw new AIServiceException(e);
}
}
示例10: FromStream
/// <summary>
/// Loads the data from an image stream and fills this WriteableBitmap with it.
/// </summary>
/// <param name="bmp">The WriteableBitmap.</param>
/// <param name="stream">The stream with the image data.</param>
/// <returns>The WriteableBitmap that was passed as parameter.</returns>
public static async Task<WriteableBitmap> FromStream(this WriteableBitmap bmp, Stream stream)
{
using (var dstStream = new InMemoryRandomAccessStream())
{
await RandomAccessStream.CopyAsync(stream.AsInputStream(), dstStream);
return await FromStream(bmp, dstStream);
}
}
示例11: WriteAppendBlockAsync
/// <summary>
/// Starts an asynchronous AppendBlock operation as soon as the parallel
/// operation semaphore becomes available. Since parallelism is always set
/// to 1 for append blobs, appendblock operations are called serially.
/// </summary>
/// <param name="blockData">Data to be uploaded</param>
/// <param name="offset">Offset within the append blob to be used to set the append offset conditional header.</param>
/// <param name="blockMD5">MD5 hash of the data to be uploaded</param>
/// <returns>A task that represents the asynchronous write operation.</returns>
private async Task WriteAppendBlockAsync(Stream blockData, long offset, string blockMD5)
{
this.noPendingWritesEvent.Increment();
await this.parallelOperationSemaphore.WaitAsync();
this.accessCondition.IfAppendPositionEqual = offset;
int previousResultsCount = this.operationContext.RequestResults.Count;
Task writeBlockTask = this.appendBlob.AppendBlockAsync(blockData.AsInputStream(), blockMD5, this.accessCondition, this.options, this.operationContext).AsTask().ContinueWith(task =>
{
if (task.Exception != null)
{
if (this.options.AbsorbConditionalErrorsOnRetry.Value
&& this.operationContext.LastResult.HttpStatusCode == (int)HttpStatusCode.PreconditionFailed)
{
StorageExtendedErrorInformation extendedInfo = this.operationContext.LastResult.ExtendedErrorInformation;
if (extendedInfo != null
&& (extendedInfo.ErrorCode == BlobErrorCodeStrings.InvalidAppendCondition || extendedInfo.ErrorCode == BlobErrorCodeStrings.InvalidMaxBlobSizeCondition)
&& (this.operationContext.RequestResults.Count - previousResultsCount > 1))
{
// Pre-condition failure on a retry should be ignored in a single writer scenario since the request
// succeeded in the first attempt.
Logger.LogWarning(this.operationContext, SR.PreconditionFailureIgnored);
}
else
{
this.lastException = task.Exception;
}
}
else
{
this.lastException = task.Exception;
}
}
this.noPendingWritesEvent.Decrement();
this.parallelOperationSemaphore.Release();
});
}
示例12: FromStream
/// <summary>
/// Loads the data from an image stream and returns a new WriteableBitmap.
/// </summary>
/// <param name="stream">The stream with the image data.</param>
/// <param name="pixelFormat">The pixel format of the stream data. If Unknown is provided as param, the default format of the BitmapDecoder is used.</param>
/// <returns>A new WriteableBitmap containing the pixel data.</returns>
public static async Task<WriteableBitmap> FromStream(Stream stream, BitmapPixelFormat pixelFormat = BitmapPixelFormat.Unknown)
{
using (var dstStream = new InMemoryRandomAccessStream())
{
await RandomAccessStream.CopyAsync(stream.AsInputStream(), dstStream);
return await FromStream(dstStream);
}
}
示例13: UploadFileStreamAsync
// Summary:
// Upload files by output stream.
//
// Parameters:
// sourceFolderId:
// The id of the place you want to upload.
//
// fileName:
// The name you want to use after upload.
//
// Returns:
// The StorageFolder where you downloaded folder.
public async Task<bool> UploadFileStreamAsync(string folderIdToStore, string fileName, Stream outstream)
{
//ProgressBar progressBar = new ProgressBar();
//progressBar.Value = 0;
//var progressHandler = new Progress<LiveOperationProgress>(
// (progress) => { progressBar.Value = progress.ProgressPercentage; });
System.Threading.CancellationTokenSource ctsUpload = new System.Threading.CancellationTokenSource();
try
{
//LiveOperationResult result = await this.LiveClient
// .UploadAsync(folderIdToStore, fileName, outstream, OverwriteOption.Overwrite, ctsUpload.Token, progressHandler);
LiveOperationResult result = await this.LiveClient.BackgroundUploadAsync(folderIdToStore, fileName, outstream.AsInputStream(), OverwriteOption.Overwrite);
}
catch
{
ctsUpload.Cancel();
throw new ShareException(fileName, ShareException.ShareType.UPLOAD);
}
return true;
}
示例14: LoadStrokesFromStream
private async void LoadStrokesFromStream(Stream stream)
{
await inkManager.LoadAsync(stream.AsInputStream());
needToRedrawInkSurface = true;
}
示例15: JsonStreamCommandReader
public JsonStreamCommandReader(Stream stream)
{
_dataReader = new DataReader(stream.AsInputStream());
}