private void CreateFile(byte[] outByteArray)
{
//Create a new file containing the returned PDF document
string filename = "C:\\myfile.pdf";
FileStream fs2 = new FileStream(filename, FileMode.OpenOrCreate);
BinaryWriter w = new BinaryWriter(fs2);
w.Write(outByteArray);
w.Close();
fs2.Close();
}
This is my current code.
I am writing to the server's drive. It is working fine.
But now I have to write the byte array to a web folder
I mean to some folder like http://tyyet.com/rsfgqs/destination/
and save it there in the name myfile.pdf.
How can I do that?
Can I use HttpWebRequest for that?
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
string sDir = #"\\Q1875G\Vehicle";
NetworkCredential NCredentials = new NetworkCredential("FOLDER_ACCESS_USER", "Welcome#2020");
using (new NetworkConnection(sDir, NCredentials))
{
string path = $"{sDir}\\483";
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
string fileName = "add_274400.jpg";
path = $"{sDir}\\483\\{fileName}";
byte[] byteArrayIn = imageByteArray;
using (var ms = new MemoryStream(byteArrayIn))
{
using (var fs = new FileStream(path, FileMode.Create))
{
ms.WriteTo(fs);
}
}
}
Using this code image file getting created but when I try to open it, it gives an error that this is not a valid bitmap file, or its format is not currently supported.
That's not a JPEG yet; it's the bytes of a jpeg, base64 encoded, and prefixed with a header that would make it suitable for plonking inline into an <img src= tag attribute
The jpeg data starts with the /9j so you'll have to do something like:
var b64jpeg = Encoding.ASCII.GetString(imageByteArray, 23, imageByteArray.Length - 23);
var jpegBytes = Convert.FromBase64String(b64jpeg);
Then write jpegBytes to a file. There is no need to put it in a MemoryStream first; just File.WriteAllBytes it
If this imageByteArray has been delivered to you as a string (outside the code visible in the question) it would be better to keep it as that and substring it, rather than having this "to array (in the other code), from array (in this code)" step
Side note: you don't need if (!Directory.Exists(path)) either; Directory.CreateDirectory does nothing if the directory exists, so just call it without the Exists check
In my application there are some files. Which I want to be able to copy and paste elsewhere in application.
The file I want to copy and paste I have stored inside a function GetPartialExportString()
My Idea:
When User clicks on "Copy" I create one file somewhere on comp and store it inside new created file
When user clicks "Paste" I Read from the file I generated when I clicked copy and add it there.
MemoryStream destinationStream = new MemoryStream();
protected void CopyCommand()
{
var modelAsString = GetPartialExportString();
string fileName = "copy.xaml";
string targetPath = #"C:\Users\";
string destFile = System.IO.Path.Combine(targetPath, fileName);
//System.IO.Directory.CreateDirectory(targetPath);
// convert string to stream
byte[] byteArray = Encoding.UTF8.GetBytes(modelAsString);
MemoryStream readingStream = new MemoryStream(byteArray);
FileStream file = new FileStream(fileName, FileMode.Create, FileAccess.Write);
readingStream.WriteTo(file);
file.Close();
readingStream.Close();
readingStream.CopyTo(destinationStream);
File.WriteAllText(destFile, modelAsString);
}
protected void PasteCommand()
{
string importString = File.ReadAllText("d:\\temp.txt");
LoadUnitFromXamlString("d:\\temp.txt");
}
It does not work like this. New to this, if someone can help I would appreciate!
File routes are incorect at the moment. But even when they were normal it was not working!
You should avoid overriding Close() method of Stream class for MemoryStream/FileStream objects. Use Dispose() instead.
You should get all the work done by the stream objects first and then dispose them.
After you've copied the contents of readingStream object to file, you'll have to readjust the position of stream buffer to the beginning of the contents present in readingStream object so as to copy it successfully to destinationStream.
Modify your code snippet like this:
readingStream.WriteTo(file);
readingStream.Position = 0;
readingStream.CopyTo(destinationStream);
file.Dispose();
readingStream.Dispose();
File.WriteAllText(destFile, modelAsString);
I have developed an ASP.net C# function to upload PDF to the Database. when I try it in LocalHost, its working perfectly fine. but when I publish it in a server on IIS. it gives me the below error when I click upload:
System.IO.DirectoryNotFoundException: Could not find a part of the
path + <path of the file>
string filePath = Path.GetFullPath(FileUpload1.PostedFile.FileName);
string filename = Path.GetFileName(filePath);
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
br.Close();
fs.Close();
Is there anything I should change in order to be able to upload?
When you access it from localhost, both client and server are same so it can find file. but when you publish both the machine are isolated. basically you are not getting content from uploaded file, what you did is get the filename and fetch data from local hard disk, you should use following snippet.
int fileLen = fu.PostedFile.ContentLength;
Byte[] Input = new Byte[fileLen];
Stream myStream = fu.PostedFile.InputStream;
myStream.Read(Input, 0, Input.Length);
I have declared an byte array with size of bytes in uploaded file. and read byte from PostedFile InputStream.
I have .DAT from SharePoint, to recover some of the data I need to read the .DAT file using C#.
Some of the options are
StreamReader objInput = new StreamReader(filename, System.Text.Encoding.Default);
string contents = objInput.ReadToEnd().Trim();
string[] split = System.Text.RegularExpressions.Regex.Split(contents, "\\s+", RegexOptions.None);
foreach (string s in split)
{
Console.WriteLine(s);
}
or
//ObjectToSerialize objectToSerialize;
//Stream stream = File.Open(filename, FileMode.Open);
//BinaryFormatter bFormatter = new BinaryFormatter();
//objectToSerialize = (ObjectToSerialize)bFormatter.Deserialize(stream);
//stream.Close();
.../
The problem is the DAT file may contain XMl files, Doc files, or PPT or others. I just want list all the data and files inside the .DAT file.
Is there is any way I can do this is C#?
You can read .dat file using c#, but it depends on the structure of data how you have inside the .dat file
take a look at this link
How-read-data-from-DAT-file-using-C
how-can-i-read-data-from-dat-files