Hopefully something simple but have tried and tried and keep failing.
I am attempting to create a Stream object in a C# application that will copy a CSS file to a specific location.
The CSS file is embedded in my resources.
Regardles of what I have tried the stream object is always null.
Can somebody please point in the right direction by looking at the below?
Thanks :) burrows111
Assembly Assemb = Assembly.GetExecutingAssembly();
Stream stream = Assemb.GetManifestResourceStream(ThisNameSpace.Properties.Resources.ClockingsMapStyle); // NULL!!!!
FileStream fs = new FileStream("to store in this location", FileMode.Create);
StreamReader Reader = new StreamReader(stream);
StreamWriter Writer = new StreamWriter(fs);
Writer.Write(Reader.ReadToEnd());
This works for me:
StreamReader reader;
StreamWriter writer;
Stream stream;
Assembly assembly = Assembly.GetExecutingAssembly();
using (stream = assembly.GetManifestResourceStream("Namespace.Stylesheet1.css"))
using (reader = new StreamReader(stream))
using (writer = new StreamWriter("test.css"))
{
string content = reader.ReadToEnd();
writer.Write(content);
writer.Close();
}
I tried it in a standard Windows Forms app.
EDIT: The file (Stylesheet1.css) was included as a normal item in the project with a build action of "Embedded Resource".
Related
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
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.
I am trying to write a html file using stream writer in c#, it is overwriting the file if close the application and run again, but its appending when I tried to write file for different scenario without closing the application. I wants to overwrite in second case also.
using (FileStream fs = new FileStream("Report.html", FileMode.Create, FileAccess.Write))
{
using (StreamWriter w = new StreamWriter(fs, Encoding.UTF8))
{
w.WriteLine(html);
}
}
To append to the end of your file:
File.AppendAllText("Report.html", html, Encoding.UTF8);
To overwrite your file:
File.WriteAllText("Report.html", html, Encoding.UTF8);
Try explicitly closing the writer and stream instead of depending upon you using () expression to do that for you.
My problem is that I can't find a solution to decompress a file. Compressing a file works without error messages, but I don't know if that's right.
Here is my code for compressing a file:
using (StreamReader sr = new StreamReader(File.Open(srcFile, FileMode.Open), true))
using (GZipStream zip = new GZipStream(File.Open(destFile, FileMode.OpenOrCreate), CompressionMode.Compress, false))
using (StreamWriter sw = new StreamWriter(zip, Encoding.UTF8)) {
while (!sr.EndOfStream) {
sw.Write((char)sr.Read());
}
}
Then I tried to decompress the compressed file with following code:
using (GZipStream zip = new GZipStream(File.Open(srcFile, FileMode.Open), CompressionMode.Decompress, false))
using (StreamReader sr = new StreamReader(zip, true))
using (StreamWriter sw = new StreamWriter(File.Open(destFile, FileMode.OpenOrCreate), Encoding.UTF8)) {
while (!sr.EndOfStream) {
sw.Write((char)sr.Read());
}
}
The content of the decompressed file wasn't like the content of the source file and I don't know where I've made my mistakes.
Thanks in advance for your help.
I'm sorry for my bad English, but English isn't my strength. :/
Using StreamReader/Writer is not indicated. It will certainly destroy the file content if the file is not a text file. And the decompressed file will always have a BOM, it might be missing in the original file.
There's just no reason to use these classes, GZipStream doesn't care. Use FileStream instead, the only way to be sure that the decompressed bytes are an exact match with the bytes in the original file.
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");