本文整理汇总了C#中Stream.WriteTo方法的典型用法代码示例。如果您正苦于以下问题:C# Stream.WriteTo方法的具体用法?C# Stream.WriteTo怎么用?C# Stream.WriteTo使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Stream
的用法示例。
在下文中一共展示了Stream.WriteTo方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Write
public void Write(Stream stream)
{
using (var fs = File.OpenWrite())
{
stream.WriteTo(fs);
}
}
示例2: ToXml
XElement ToXml(Stream stream)
{
using (var output = new MemoryStream())
{
stream.WriteTo(output);
output.Position = 0;
var bytes = new byte[output.Length];
output.Read(bytes, 0, bytes.Length);
var xml = Ionic.Zlib.GZipStream.UncompressString(bytes);
return XDocument.Parse(xml).Root;
}
}
示例3: Load
public override void Load(OpenedFile file, Stream stream)
{
if (file == PrimaryFile) {
try {
XmlDocument doc = new XmlDocument();
doc.Load(stream);
setDoc = new SettingsDocument(doc.DocumentElement, view);
view.ShowEntries(setDoc.Entries);
} catch (XmlException ex) {
ShowLoadError(ex.Message);
}
} else if (file == appConfigFile) {
appConfigStream = new MemoryStream();
stream.WriteTo(appConfigStream);
}
}
示例4: Save
public string Save(Stream stream, string filename, string username)
{
string userFolder = Path.Combine(_root, username);
if (!Directory.Exists(userFolder))
{
Directory.CreateDirectory(userFolder);
}
string storageFile = Path.Combine(userFolder, filename);
if (File.Exists(storageFile))
{
File.Delete(storageFile);
}
using (Stream file = File.Create(storageFile))
{
stream.WriteTo(file);
}
return storageFile;
}
示例5: WritePageImpl
/// <summary>
/// Implementation method for the WritePage methods.
/// </summary>
/// <param name="pageData">The page data.</param>
/// <param name="startOffset">The start offset.</param>
/// <param name="sourceStreamPosition">The beginning position of the source stream prior to execution, negative if stream is unseekable.</param>
/// <param name="options">An object that specifies any additional options for the request.</param>
/// <returns>A <see cref="TaskSequence"/> that writes the pages.</returns>
private TaskSequence WritePageImpl(Stream pageData, long startOffset, long sourceStreamPosition, BlobRequestOptions options)
{
CommonUtils.AssertNotNull("options", options);
long length = pageData.Length;
// Logic to rewind stream on a retry
// HACK : for non seekable streams we need a way to detect the retry iteration so as to only attempt to execute once.
// The first attempt will have SourceStreamPosition = -1, which means the first iteration on a non seekable stream.
// The second attempt will have SourceStreamPosition = -2, anything below -1 is considered an abort. Since the Impl method
// does not have an executino context to be aware of what iteration is used the SourceStreamPosition is utilized as counter to
// differentiate between the first attempt and a retry.
if (sourceStreamPosition >= 0 && pageData.CanSeek)
{
if (sourceStreamPosition != pageData.Position)
{
pageData.Seek(sourceStreamPosition, 0);
}
}
else if (sourceStreamPosition < -1)
{
// TODO : Need to rewrite this to support buffering in XSCL2 so that retries can work on non seekable streams
throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, SR.CannotRetryNonSeekableStreamError));
}
if (startOffset % Protocol.Constants.PageSize != 0)
{
CommonUtils.ArgumentOutOfRange("startOffset", startOffset);
}
// TODO should reuse sourceStreamPoisition when the HACK above is removed, for readability using a new local variable
long rangeStreamOffset = pageData.CanSeek ? pageData.Position : 0;
PutPageProperties properties = new PutPageProperties()
{
Range = new PageRange(startOffset, startOffset + length - rangeStreamOffset - 1),
PageWrite = PageWrite.Update,
};
if ((1 + properties.Range.EndOffset - properties.Range.StartOffset) % Protocol.Constants.PageSize != 0 ||
(1 + properties.Range.EndOffset - properties.Range.StartOffset) == 0)
{
CommonUtils.ArgumentOutOfRange("pageData", pageData);
}
var webRequest = ProtocolHelper.GetWebRequest(
this.ServiceClient,
options,
(timeout) => BlobRequest.PutPage(this.TransformedAddress, timeout, properties, null));
////BlobRequest.AddMetadata(webRequest, this.Metadata);
// Retrieve the stream
var requestStreamTask = webRequest.GetRequestStreamAsync();
yield return requestStreamTask;
// Copy the data
using (var outputStream = requestStreamTask.Result)
{
var copyTask = new InvokeTaskSequenceTask(() => { return pageData.WriteTo(outputStream); });
yield return copyTask;
// Materialize any exceptions
var scratch = copyTask.Result;
}
// signing request needs Size to be set
this.ServiceClient.Credentials.SignRequest(webRequest);
// Get the response
var responseTask = webRequest.GetResponseAsyncWithTimeout(this.ServiceClient, options.Timeout);
yield return responseTask;
// Parse the response
using (HttpWebResponse webResponse = responseTask.Result as HttpWebResponse)
{
this.ParseSizeAndLastModified(webResponse);
}
}
示例6: UploadData
/// <summary>
/// Uploads the data into the web request.
/// </summary>
/// <param name="request">The request that is setup for a put.</param>
/// <param name="source">The source of data.</param>
/// <param name="result">The response from the server.</param>
/// <returns>The sequence used for uploading data.</returns>
internal TaskSequence UploadData(HttpWebRequest request, Stream source, Action<WebResponse> result)
{
// Retrieve the stream
var requestStreamTask = request.GetRequestStreamAsync();
yield return requestStreamTask;
// Copy the data
using (var outputStream = requestStreamTask.Result)
{
var copyTask = new InvokeTaskSequenceTask(() => { return source.WriteTo(outputStream); });
yield return copyTask;
// Materialize any exceptions
var scratch = copyTask.Result;
}
// Get the response
var responseTask = request.GetResponseAsyncWithTimeout(this.ServiceClient, this.ServiceClient.Timeout);
yield return responseTask;
// Return the response object
var response = responseTask.Result;
result(response);
}
示例7: StoreFile
private void StoreFile(string filename, Stream contentStream)
{
using (var file = File.Create(filename))
{
contentStream.WriteTo(file);
}
}
示例8: UploadFile
public static void UploadFile(this WebRequest webRequest, Stream fileStream, string fileName, string mimeType)
{
var httpReq = (HttpWebRequest)webRequest;
httpReq.UserAgent = Env.ServerUserAgent;
httpReq.Method = "POST";
httpReq.AllowAutoRedirect = false;
httpReq.KeepAlive = false;
var boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
httpReq.ContentType = "multipart/form-data; boundary=" + boundary;
using (var ms = new MemoryStream())
{
var boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
var headerTemplate = "\r\n--" + boundary +
"\r\nContent-Disposition: form-data; name=\"file\"; filename=\"{0}\"\r\nContent-Type: {1}\r\n\r\n";
var header = string.Format(headerTemplate, fileName, mimeType);
var headerbytes = System.Text.Encoding.ASCII.GetBytes(header);
ms.Write(headerbytes, 0, headerbytes.Length);
fileStream.WriteTo(ms);
ms.Write(boundarybytes, 0, boundarybytes.Length);
httpReq.ContentLength = ms.Length;
var requestStream = httpReq.GetRequestStream();
ms.Position = 0;
ms.WriteTo(requestStream);
requestStream.Close();
}
}
示例9: WriteFile
/// <summary>
/// Creates or updates a given file resource in the file system.
/// </summary>
/// <param name="parentFolderPath">The qualified path of the parent folder that will
/// contain the file.</param>
/// <param name="fileName">The name of the file to be created.</param>
/// <param name="input">A stream that provides the file's contents.</param>
/// <param name="overwrite">Whether an existing file should be overwritten
/// or not. If this parameter is false and the file already exists, a
/// <see cref="ResourceOverwriteException"/> is thrown.</param>
/// <exception cref="VirtualResourceNotFoundException">If the parent folder
/// does not exist.</exception>
/// <exception cref="ResourceAccessException">In case of invalid or prohibited
/// resource access.</exception>
/// <exception cref="ResourceOverwriteException">If a file already exists at the
/// specified location, and the <paramref name="overwrite"/> flag was not set.</exception>
/// <exception cref="ArgumentNullException">If any of the parameters is a null reference.</exception>
public override VirtualFileInfo WriteFile(string parentFolderPath, string fileName, Stream input, bool overwrite)
{
if (parentFolderPath == null) throw new ArgumentNullException("parentFolderPath");
if (fileName == null) throw new ArgumentNullException("fileName");
if (input == null) throw new ArgumentNullException("input");
//get the parent and make sure it exists
string absoluteParentPath;
var parent = GetFolderInfoInternal(parentFolderPath, true, out absoluteParentPath);
if(RootDirectory == null && parent.IsRootFolder)
{
VfsLog.Debug("Blocked attempt to create a file '{0}' at system root (which is the machine itself - no root directory was set).", fileName);
throw new ResourceAccessException("Files cannot be created at the system root.");
}
//combine to file path and get virtual file (also makes sure we don't get out of scope)
string absoluteFilePath = PathUtil.GetAbsolutePath(fileName, new DirectoryInfo(absoluteParentPath));
FileInfo fi = new FileInfo(absoluteFilePath);
if (fi.Exists && !overwrite)
{
VfsLog.Debug("Blocked attempt to overwrite file '{0}'", fi.FullName);
string msg = String.Format("The file [{0}] already exists.", fileName);
throw new ResourceOverwriteException(msg);
}
try
{
using (Stream writeStream = new FileStream(fi.FullName, FileMode.Create, FileAccess.Write, FileShare.None))
{
input.WriteTo(writeStream);
}
}
catch (Exception e)
{
//log exception with full path
string msg = "Could not write write submitted content to file '{0}'.";
VfsLog.Error(e, msg, fi.FullName);
//generate exception with relative path
msg = String.Format(msg, PathUtil.GetRelativePath(fi.FullName, RootDirectory));
throw new ResourceAccessException(msg, e);
}
//return update file info
var file = fi.CreateFileResourceInfo();
//adjust and return
if (UseRelativePaths) file.MakePathsRelativeTo(RootDirectory);
return file;
}
示例10: AppendFile
public void AppendFile(string filePath, Stream stream)
{
var realFilePath = RootDir.RealPath.CombineWith(filePath);
EnsureDirectory(Path.GetDirectoryName(realFilePath));
using (var fs = new FileStream(realFilePath, FileMode.Append))
{
stream.WriteTo(fs);
}
}
示例11: WriteFileStreamToFileSystem2
protected void WriteFileStreamToFileSystem2(FileItem fileItem, Stream input) {
input.WriteTo(fileItem.LocalFile.FullName);
}