Save a HTTP stream to file in c#
This is a tricky situation. The problem is you read the HttpResponseStream
already. As a result, you're at the end of the stream. Under normal circumstances you'd just set dataStream.Position = 0
. However, you can't do that here because we're not talking about a file on your PC, it's a network stream so you can't "go backwards" (it was already sent to you). As a result, what I'd recommend you do is instead of trying to write the original stream again, write your XmlDocument
.
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
XmlDocument events = new XmlDocument();
events.Load(reader);
events.Save("C:\\XMLfiles\\test.xml");
In that case it will work since you're saving the data that's been copied to the XmlDocument
rather than trying to reread a network stream.
How to write to a stream then to file
This should do the job for you:
private void SaveString(string data)
{
var byteData = Encoding.UTF8.GetBytes(data);
var saveFileDialog = new SaveFileDialog
{
DefaultExt = "json",
AddExtension = true,
Filter = "JSON|*.json"
};
if (saveFileDialog.ShowDialog() != DialogResult.OK ||
string.IsNullOrEmpty(saveFileDialog.FileName)) return;
using (var saveFileDialogStream = saveFileDialog.OpenFile())
{
saveFileDialogStream.Write(byteData, 0, byteData.Length);
}
}
C# write memorystream to file
you don't need any StreamReader, just do it like this:
public void WriteToFile(Stream stream)
{
stream.Seek(0, SeekOrigin.Begin);
using(var fs = new FileStream("/path/to/file", FileMode.OpenOrCreate))
{
stream.CopyTo(fs);
}
}
//var memoryStream...
//...
WriteFoFile(memoryStream);
Writing a memory stream to a file
There is a very handy method, Stream.CopyTo(Stream)
.
using (MemoryStream ms = new MemoryStream())
{
StreamWriter writer = new StreamWriter(ms);
writer.WriteLine("asdasdasasdfasdasd");
writer.Flush();
//You have to rewind the MemoryStream before copying
ms.Seek(0, SeekOrigin.Begin);
using (FileStream fs = new FileStream("output.txt", FileMode.OpenOrCreate))
{
ms.CopyTo(fs);
fs.Flush();
}
}
Also, you don't have to close fs
since it's in a using statement and will be disposed at the end.
saving a file (from stream) to disk using c#
For file Type you can rely on FileExtentions and for writing it to disk you can use BinaryWriter. or a FileStream.
Example (Assuming you already have a stream):
FileStream fileStream = File.Create(fileFullPath, (int)stream.Length);
// Initialize the bytes array with the stream length and then fill it with data
byte[] bytesInStream = new byte[stream.Length];
stream.Read(bytesInStream, 0, bytesInStream.Length);
// Use write method to write to the file specified above
fileStream.Write(bytesInStream, 0, bytesInStream.Length);
//Close the filestream
fileStream.Close();
File Stream file saving
Here's what I do and it works well. For you, filePath/filename = fileNameWitPath. Do this for each file you have. Hope it works for you. If you need further info, Id be glad to help.
using (var stream = File.Create(filePath + filename))
{
attachment.ContentObject.DecodeTo(stream, cancel.Token);
}
Save and load MemoryStream to/from a file
You may use MemoryStream.WriteTo
or Stream.CopyTo
(supported in framework version 4.5.2, 4.5.1, 4.5, 4) methods to write content of memory stream to another stream.
memoryStream.WriteTo(fileStream);
Update:
fileStream.CopyTo(memoryStream);
memoryStream.CopyTo(fileStream);
Is this a good way to save stream to file in Universal App, Windows 10?
If I understand correctly, you were trying to save the imageStream(IRandomAccessStream) to a coverFile(StrorageFile).
AsStreamForWrite and AsStreamForRead are both the Windows Runtime extension methods in .NET. In this case, you don’t need to convert Windows Runtime Stream to .NET IO stream (it will take some extra performance cost). I will suggest you using the way as following (without using .NET class library).
var src = await KnownFolders
.PicturesLibrary
.GetFileAsync("210644575939381015.jpg")
.AsTask();
var target = await KnownFolders
.PicturesLibrary
.CreateFileAsync("new_file.jpg")
.AsTask();
using (var srcStream = await src.OpenAsync(FileAccessMode.Read))
using (var targetStream = await target.OpenAsync(FileAccessMode.ReadWrite))
using (var reader = new DataReader(srcStream.GetInputStreamAt(0)))
{
var output = targetStream.GetOutputStreamAt(0);
await reader.LoadAsync((uint)srcStream.Size);
while (reader.UnconsumedBufferLength > 0)
{
uint dataToRead = reader.UnconsumedBufferLength > 64
? 64
: reader.UnconsumedBufferLength;
IBuffer buffer = reader.ReadBuffer(dataToRead);
await output.WriteAsync(buffer);
}
await output.FlushAsync();
}
Related Topics
Best Way to Implement Keyboard Shortcuts in a Windows Forms Application
Does C# Support Return Type Covariance
Using Xpath With Default Namespace in C#
What Is an "Index Out of Range" Exception, and How to Fix It
Why Xml-Serializable Class Need a Parameterless Constructor
How to Open a Chrome Profile Through --User-Data-Dir Argument of Selenium
C# Lambda Expressions: Why Should I Use Them
Memory Leak Using Streamreader and Xmlserializer
Is There a Better Alternative Than This to 'Switch on Type'
Listen For Key Press in .Net Console App
Can You Call Directory.Getfiles() With Multiple Filters
What's a "Static Method" in C#
Filesystemwatcher VS Polling to Watch For File Changes
Unity Scripts Edited in Visual Studio Don't Provide Autocomplete
The Provider Is Not Compatible With the Version of Oracle Client
How to Add Extension Methods to an Existing Static Class
How to Remove All HTML Tags from a String Without Knowing Which Tags Are in It