Writing a stream of content to file in c# - c#

I have a variable which holds a stream of content .
The variable is speicified as shown below ,
Task<Stream> tempStream = ....
Specifically this tempStream variable holds a A pdf stream.
I want to to write this stream into a file . How can I do this in c# ?

the following should work:
path = #"Path\\to\\output";
using (FileStream outputFileStream = new FileStream(path, FileMode.Create))
{
tempStream.CopyTo(outpoutFileStream);
}

Related

How to copy or grab a file from stream and copy it to a folder in the server

I am using syncfusion OCR to scan PDFs which produces a document and push it for download as the end result. I am trying to grab the file from the stream and put copy it to my server but i am getting an error saying stream does not support reading. Here is my code
try
{
string binaries = Path.Combine(this._hostingEnvironment.ContentRootPath, "Tesseractbinaries", "Windows");
//Initialize OCR processor with tesseract binaries.
OCRProcessor processor = new OCRProcessor(binaries);
//Set language to the OCR processor.
processor.Settings.Language = Languages.English;
string path = Path.Combine(this._hostingEnvironment.ContentRootPath, #"Data\font", "times.ttf");
FileStream fontStream = new FileStream(path, FileMode.Open);
//Create a true type font to support unicode characters in PDF.
processor.UnicodeFont = new PdfTrueTypeFont(fontStream, 8);
//Set temporary folder to save intermediate files.
processor.Settings.TempFolder = Path.Combine(this._hostingEnvironment.ContentRootPath, "Data");
//Load a PDF document.
FileStream inputDocument = new FileStream(Path.Combine(this._hostingEnvironment.ContentRootPath, "Data", "pistone.pdf"), FileMode.Open);
PdfLoadedDocument loadedDocument = new PdfLoadedDocument(inputDocument);
//Perform OCR with language data.
string tessdataPath = Path.Combine(this._hostingEnvironment.ContentRootPath, "tessdata");
//string tessdataPath = Path.Combine(#"tessdata");
processor.PerformOCR(loadedDocument, tessdataPath);
//Save the PDF document.
MemoryStream outputDocument = new MemoryStream();
loadedDocument.Save(outputDocument);
outputDocument.Position = 0;
//Dispose OCR processor and PDF document.
processor.Dispose();
loadedDocument.Close(true);
//Download the PDF document in the browser.
FileStreamResult fileStreamResult = new FileStreamResult(outputDocument, "application/pdf");
fileStreamResult.FileDownloadName = "OCRed_PDF_document.pdf";
//setting a path for saving it to my server and copying it to the folder downloads
string filePath = Path.Combine("downloads", fileStreamResult.FileDownloadName);
using (Stream fileStream = new FileStream(filePath, FileMode.Append, FileAccess.Write))
{
fileStream.CopyTo(fileStream);
}
return fileStreamResult;
}
catch (Exception ex)
{
throw;
}
fileStream.CopyTo(fileStream) seems to be attempting to copy a stream to itself.
Try replacing with fileStreamResult.FileStream.CopyTo(fileStream) ?
We can resolve this error by using fileStreamResult.FileStream.CopyTo(fileStream) instead of fileStream.CopyTo(fileStream) in sample level. Please try the below code snippet or sample on your end and let us know the result.
Please find the below modified code snippet,
using (Stream fileStream = new FileStream(filePath, FileMode.Append, FileAccess.Write)){ fileStreamResult.FileStream.CopyTo(fileStream);}
Please refer to the below link for more information,
UG: https://help.syncfusion.com/file-formats/pdf/working-with-ocr/dot-net-core
KB: https://www.syncfusion.com/kb/11696/how-to-perform-ocr-in-asp-net-core-platform

ArgumentException in StreamWriter in Xamarin.Forms

I am writing a Xamarin.Form PLC for Android and iOS, and have a place where I need to write some application stuff to a text file embedded resource. I've implemented reading from the same text file successfully, with same syntax just using StreamReader, but the StreamWriter implementation looks like this:
Assembly assembly = GetType().GetTypeInfo().Assembly;
string resource = "jetStream.Results.settings.txt";
using (Stream stream = assembly.GetManifestResourceStream(resource)) {
using (StreamWriter writer = new StreamWriter(stream)) {
//do stuff
}
}
StreamWriter is throwing an argument of "Stream is not writeable" at System.IO.StreamWriter. Am I doing something obvsiously wrong? Why is the Stream Readable but not Writeable using the same assembly/resource/stream construction?
The stream from GetManifestResourceStream is not writable. The stream's file is embedded in the assembly at build time and cannot be changed. You'll have to write the file to disk before you can write to it.
string resource = "jetStream.Results.settings.txt";
using (Stream stream = assembly.GetManifestResourceStream(resource))
using (var fs = new FileStream(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal)), FileMode.Create, FileAccess.Write))
using (var stream = new MemoryStream())
using (var writer = new StreamWriter(fs))
{
rStream.Stream.CopyTo(stream);
writer.Write(stream.ToArray());
}
After this you can read and write to the file on disk.
Depending on what you want to write, if it's just things like application settings, you can use the Application.Properties collection http://www.kymphillpotts.com/exploring-xamarin-forms-1-3-properties-dictionary/ otherwise I agree with Jon's answer.

Is it possible to change file content directly in zip file?

I have form with text box and customer wants to store all changes from this textbox to zip archive.
I am using http://dotnetzip.codeplex.com
and i have example of code:
using (ZipFile zip = new ZipFile())
{
zip.AddFile("text.txt");
zip.Save("Backup.zip");
}
And i dont want to create each time temp text.txt and zip it back.
Can I access text.txt as Stream inside zip file and save text there?
There is an example in DotNetZip that use a Stream with the method AddEntry.
String zipToCreate = "Content.zip";
String fileNameInArchive = "Content-From-Stream.bin";
using (System.IO.Stream streamToRead = MyStreamOpener())
{
using (ZipFile zip = new ZipFile())
{
ZipEntry entry= zip.AddEntry(fileNameInArchive, streamToRead);
zip.Save(zipToCreate); // the stream is read implicitly here
}
}
A little test using LinqPad shows that it is possible to use a MemoryStream to build the zip file
void Main()
{
UnicodeEncoding uniEncoding = new UnicodeEncoding();
byte[] firstString = uniEncoding.GetBytes("This is the current contents of your TextBox");
using(MemoryStream memStream = new MemoryStream(100))
{
memStream.Write(firstString, 0 , firstString.Length);
// Reposition the stream at the beginning (otherwise an empty file will be created in the zip archive
memStream.Seek(0, SeekOrigin.Begin);
using (ZipFile zip = new ZipFile())
{
ZipEntry entry= zip.AddEntry("TextBoxData.txt", memStream);
zip.Save(#"D:\temp\memzip.zip");
}
}
}
There is another DotNetZip method accepting a file path as an argument:
zip.RemoveEntry(entry);
zip.AddEntry(entry.FileName, text, ASCIIEncoding.Unicode);

unable to save dynamically created MemoryStream with rebex sftp

I'm using StreamWriter to generate a dynamic file and holding it in a MemoryStream. Everything appears to be alright until I go to save the file using rebex sftp.
The example they give on their site works fine:
// upload a text using a MemoryStream
string message = "Hello from Rebex FTP for .NET!";
byte[] data = System.Text.Encoding.Default.GetBytes(message);
System.IO.MemoryStream ms = new System.IO.MemoryStream(data);
client.PutFile(ms, "message.txt");
However the code below does not:
using (var stream = new MemoryStream())
{
using (var writer = new StreamWriter(stream))
{
writer.AutoFlush = true;
writer.Write("test");
}
client.PutFile(stream, "test.txt");
}
The file "test.txt" is saved, however it is empty. Do I need to do more than just enable AutoFlush for this to work?
After writing to the MemoryStream, the stream is positioned at the end. The PutFile method reads from the current position to the end. That's exactly 0 bytes.
You need to position the stream at the beginning before passing it to PutFile:
...
}
stream.Seek(0, SeekOrigin.Begin);
client.PutFile(stream, "test.txt");
You may also need to prevent the StreamWriter from disposing the MemoryStream:
var writer = new StreamWriter(stream);
writer.Write("test");
writer.Flush();
stream.Seek(0, SeekOrigin.Begin);
client.PutFile(stream, "test.txt");

create file and save to it using memorystream

How can i create a file and write to it using the memory stream?
I need to use the memorystream to prevent other threads from trying to access the file.
The data i'm trying to save to a file is html.
How can this be done?
(Presuming you mean how to copy a file's content to a memory stream)
If you are using framework 4:
var memoryStream = new MemoryStream();
using var fileStream = new FileStream(FilePath, FileMode.Open, FileAccess.Read);
fileStream.CopyTo(memoryStream);
Here are code to create file
byte[] data = System.Text.Encoding.ASCII.GetBytes("This is a sample string");
System.IO.MemoryStream ms = new System.IO.MemoryStream();
ms.Write(data, 0, data.Length);
ms.Close();

Categories